Ejemplo n.º 1
0
class Light(Agent):

    states = [
        State(name='off', on_enter=['set_off']),
        State(name='low', on_enter=['set_low']),
        State(name='medium', on_enter=['set_medium']),
        State(name='high', on_enter=['set_high'])
    ]

    def __init__(self, unique_id, model, room):
        super().__init__(unique_id, model)

        self.room = room
        self.wait_off = 15
        self.luminosity = 500

        self.machine = Machine(model=self, states=Light.states, initial='off')
        self.machine.add_transition('switch_off', '*', 'off')
        self.machine.add_transition('switch_low', '*', 'low')
        self.machine.add_transition('switch_medium', '*', 'medium')
        self.machine.add_transition('switch_high', '*', 'high')

    def sensorCheck(self):
        userInRoom = self.model.ThereIsSomeOccupantInRoom(self.room)
        if userInRoom == True:
            if 450 > self.luminosity:
                self.switch_low()
            elif 750 > self.luminosity > 450:
                self.switch_medium()
            else:
                self.switch_high()
        else:
            if self.state != 'off':
                if self.wait_off > 0:
                    self.wait_off = self.wait_off - 1
                else:
                    self.switch_off()
                    self.wait_off = 3
            else:
                pass

    def regularBehaviour(self):
        pass

    def step(self):
        #print('light: ', self.unique_id, self.state, self.room.name)
        self.sensorCheck()

    #Metodos de entrada y salida de los estados
    def set_off(self):
        model.ramenScript.addLightState(self.room, 'low', self.model.NStep)

    def set_low(self):
        model.ramenScript.addLightState(self.room, 'medium', self.model.NStep)

    def set_medium(self):
        model.ramenScript.addLightState(self.room, 'high', self.model.NStep)

    def set_high(self):
        model.ramenScript.addLightState(self.room, 'high', self.model.NStep)
Ejemplo n.º 2
0
    def test_state_callbacks(self):
        class Model:
            def on_enter_A(self):
                pass

            def on_exit_A(self):
                pass

            def on_enter_B(self):
                pass

            def on_exit_B(self):
                pass

        states = [
            State(name='A', on_enter='on_enter_A', on_exit='on_exit_A'),
            State(name='B', on_enter='on_enter_B', on_exit='on_exit_B')
        ]

        machine = Machine(Model(), states=states)
        state_a = machine.get_state('A')
        state_b = machine.get_state('B')
        self.assertEqual(len(state_a.on_enter), 1)
        self.assertEqual(len(state_a.on_exit), 1)
        self.assertEqual(len(state_b.on_enter), 1)
        self.assertEqual(len(state_b.on_exit), 1)
Ejemplo n.º 3
0
    def test_state_callable_callbacks(self):
        class Model:
            def __init__(self):
                self.exit_A_called = False
                self.exit_B_called = False

            def on_enter_A(self, event):
                pass

            def on_enter_B(self, event):
                pass

        states = [
            State(name='A',
                  on_enter='on_enter_A',
                  on_exit='tests.test_core.on_exit_A'),
            State(name='B', on_enter='on_enter_B', on_exit=on_exit_B),
            State(name='C', on_enter='tests.test_core.AAAA')
        ]

        model = Model()
        machine = Machine(model, states=states, send_event=True, initial='A')
        state_a = machine.get_state('A')
        state_b = machine.get_state('B')
        self.assertEqual(len(state_a.on_enter), 1)
        self.assertEqual(len(state_a.on_exit), 1)
        self.assertEqual(len(state_b.on_enter), 1)
        self.assertEqual(len(state_b.on_exit), 1)
        model.to_B()
        self.assertTrue(model.exit_A_called)
        model.to_A()
        self.assertTrue(model.exit_B_called)
        with self.assertRaises(AttributeError):
            model.to_C()
Ejemplo n.º 4
0
    def __init__(self):
        ''' Constructor.
		'''
        DomainBehavior.__init__(self)

        self.state = {'status': 'IDLE', 'sigma': INFINITY}
        self.proc = 0
        self.x = {}
        self.y = {}
        self.pos = [-1] * 100
        ''' The object '''
        self.lump = Lamp()
        # The states
        self.states = [
            State(name='on', on_enter=['say_im_turned_on']),
            State(name='off', on_enter=['say_im_turned_off'])
        ]

        self.transitions = [{
            'trigger': 'illuminate',
            'source': 'off',
            'dest': 'on'
        }, {
            'trigger': 'darken',
            'source': 'on',
            'dest': 'off'
        }]

        # Initialize
        self.machine = Machine(self.lump,
                               states=self.states,
                               transitions=self.transitions,
                               initial='off')
Ejemplo n.º 5
0
 def test_ignore_invalid_triggers(self):
     a_state = State('A')
     transitions = [['a_to_b', 'A', 'B']]
     # Exception is triggered by default
     b_state = State('B')
     m1 = Machine(None, states=[a_state, b_state], transitions=transitions,
                  initial='B')
     with self.assertRaises(MachineError):
         m1.a_to_b()
     # Exception is suppressed, so this passes
     b_state = State('B', ignore_invalid_triggers=True)
     m2 = Machine(None, states=[a_state, b_state], transitions=transitions,
                  initial='B')
     m2.a_to_b()
     # Set for some states but not others
     new_states = ['C', 'D']
     m1.add_states(new_states, ignore_invalid_triggers=True)
     m1.to_D()
     m1.a_to_b()  # passes because exception suppressed for D
     m1.to_B()
     with self.assertRaises(MachineError):
         m1.a_to_b()
     # Set at machine level
     m3 = Machine(None, states=[a_state, b_state], transitions=transitions,
                  initial='B', ignore_invalid_triggers=True)
     m3.a_to_b()
Ejemplo n.º 6
0
class PC(Agent):

    states = [
        State(name='off', on_enter=['set_off']),
        State(name='on', on_enter=['set_on']),
        State(name='standby', on_enter=['set_standby'])
    ]

    def __init__(self, unique_id, model, x, y, downUp):
        super().__init__(unique_id, model)
        self.x = x
        self.y = y
        self.pos = (x, y)
        self.down_up = downUp

        self.machine = Machine(model=self, states=PC.states, initial='off')
        self.machine.add_transition('turn_on', '*', 'on')
        self.machine.add_transition('turn_standby', 'on', 'standby')
        self.machine.add_transition('turn_off', '*', 'off')

    def sensorCheck(self):
        if (self.down_up == 'u'):
            userNear = self.model.ThereIsUserUp((self.x, self.y),
                                                self.unique_id)
        else:
            userNear = self.model.ThereIsUserDown((self.x, self.y),
                                                  self.unique_id)
        if userNear == True:
            if self.state == 'on':
                pass
            else:
                actions = self.model.actionsNear
                if actions['channel'] == 'PCOff' and actions[
                        'action'] == 'TurnOnPC':
                    self.turn_on()
        else:
            if self.state == 'on':
                actions = self.model.actionsFar
                if actions['channel'] == 'PCOn' and actions[
                        'action'] == 'TurnStandbyPC':
                    self.turn_standby()
                if actions['channel'] == 'PCOn' and actions[
                        'action'] == 'TurnOffPC':
                    self.turn_off()
            else:
                pass

    def step(self):
        self.sensorCheck()

    def set_off(self):
        pass

    def set_on(self):
        pass

    def set_standby(self):
        pass
Ejemplo n.º 7
0
 def test_pass_state_instances_instead_of_names(self):
     state_A = State('A')
     state_B = State('B')
     states = [state_A, state_B]
     m = Machine(states=states, initial=state_A)
     assert m.state == 'A'
     m.add_transition('advance', state_A, state_B)
     m.advance()
     assert m.state == 'B'
Ejemplo n.º 8
0
async def run(robot: cozmo.robot.Robot):
    states = [
        State(name='LocateCube', on_enter=[], on_exit=[]),
        State(name='GetCloser', on_enter=[], on_exit=[]),
        State(name='Backup', on_enter=[], on_exit=[]),
        State(name='Stop', on_enter=[], on_exit=[]),
    ]
    transitions = [
        {
            'trigger': 'lostCube',
            'source': ['GetCloser', 'Backup', 'Stop'],
            'dest': 'LocateCube'
        },
        {
            'trigger': 'foundCube',
            'source': 'LocateCube',
            'dest': 'GetCloser'
        },
        {
            'trigger': 'tooClose',
            'source': 'GetCloser',
            'dest': 'Backup'
        },
        {
            'trigger': 'correctDistance',
            'source': ['GetCloser', 'Backup'],
            'dest': 'Stop'
        },
        {
            'trigger': 'tooFar',
            'source': 'Backup',
            'dest': 'GetCloser'
        },
    ]
    initState = 'LocateCube'
    machine = Machine(model=robot,
                      states=states,
                      transitions=transitions,
                      initial=initState,
                      ignore_invalid_triggers=True)
    imgStates = [("images/locate.png", Image.BICUBIC),
                 ("images/getcloser.png", Image.BICUBIC),
                 ("images/backup.png", Image.BICUBIC),
                 ("images/stop.png", Image.BICUBIC)]
    for img, smp in imgStates:
        image = Image.open(img)
        resizeImg = image.resize(cozmo.oled_face.dimensions(), smp)
        image = cozmo.oled_face.convert_image_to_screen_data(resizeImg,
                                                             invert_image=True)
        faceImages.append(image)
        image = cv2.imread(img, 0)
        imgs.append(image)

    while True:
        robot, key = await switch[robot.state](robot)
        if key == ord("p"):
            break
Ejemplo n.º 9
0
class Light(Agent):

    states = [
        State(name='off', on_enter=['set_off']),
        State(name='on', on_enter=['set_on'])
    ]

    def __init__(self, unique_id, model, room):
        super().__init__(unique_id, model)

        self.room = room
        self.consume = configuration.settings.consume_light_byroom_medium
        self.wait_off = int(configuration.settings.time_to_off_light * 60 *
                            100 / configuration.settings.time_by_step)

        self.machine = Machine(model=self, states=Light.states, initial='off')
        self.machine.add_transition('switch_on', '*', 'on')
        self.machine.add_transition('switch_off', '*', 'off')

    def sensorCheck(self):
        userInRoom = self.model.ThereIsSomeOccupantInRoom(self.room)
        if userInRoom == True:
            if self.state == 'on':
                pass
            else:
                self.switch_on()
        else:
            if self.state == 'on':
                if self.wait_off > 0:
                    self.wait_off = self.wait_off - 1
                else:
                    self.switch_off()
                    self.wait_off = int(
                        configuration.settings.time_to_off_light * 60 * 100 /
                        configuration.settings.time_by_step)
            else:
                pass

    def regularBehaviour(self):
        pass

    def step(self):
        #print('light: ', self.unique_id, self.state, self.room.name)
        self.model.consumeEnergy(self)
        if (self.model.modelWay != 0):
            self.sensorCheck()
        else:
            self.regularBehaviour()

    def set_off(self):
        self.model.lightsOn.remove(self)

    def set_on(self):
        self.model.lightsOn.append(self)
Ejemplo n.º 10
0
 def exit(self, event_data):
     """ Call on_exit method on state object """
     log.debug("%s.exit '%s' callback.", self.__class__.__name__, self.tag)
     if hasattr(self, 'on_exit_state') and callable(self.on_exit_state):
         try:
             self.on_exit_state(event_data)
         except:
             traceback.print_exc()
             pdb.post_mortem()
             raise
     State.exit(self, event_data)
Ejemplo n.º 11
0
 def test_pass_state_instances_instead_of_names(self):
     state_A = State('A')
     state_B = State('B')
     states = [state_A, state_B]
     m = Machine(states=states, initial=state_A)
     assert m.state == 'A'
     m.add_transition('advance', state_A, state_B)
     m.advance()
     assert m.state == 'B'
     state_B2 = State('B', on_enter='this_passes')
     with self.assertRaises(ValueError):
         m.add_transition('advance2', state_A, state_B2)
Ejemplo n.º 12
0
    def _load_state(self, state):
        self.logger.debug("Loading state: {}".format(state))
        s = None
        try:
            state_module = load_module('pocs.state.states.{}.{}'.format(
                self._state_table_name, state))

            # Get the `on_enter` method
            self.logger.debug("Checking {}".format(state_module))

            on_enter_method = getattr(state_module, 'on_enter')
            setattr(self, 'on_enter_{}'.format(state), on_enter_method)
            self.logger.debug("Added `on_enter` method from {} {}".format(
                state_module, on_enter_method))

            self.logger.debug("Created state")
            s = State(name=state)

            s.add_callback('enter', '_update_status')

            if can_graph:
                s.add_callback('enter', '_update_graph')

            s.add_callback('enter', 'on_enter_{}'.format(state))

        except Exception as e:
            raise error.InvalidConfig(
                "Can't load state modules: {}\t{}".format(state, e))

        return s
Ejemplo n.º 13
0
 def __init__(self, *args, document, **kwargs):
     if 'tag' not in kwargs:
         kwargs['tag'] = self.__class__.__name__
     name = kwargs.get('name', kwargs['tag'])
     self.document = document
     # node consumes data
     Node.__init__(self, *args, **kwargs)
     State.__init__(
         self,
         name,
         on_enter=kwargs.get('on_enter'),
         on_exit=kwargs.get('on_exit'),
         ignore_invalid_triggers=kwargs.get('ignore_invalid_triggers'))
     self.data = self
Ejemplo n.º 14
0
class WaitForUserFSM(BrainFSM):
    states = [
        State(name='wait_for_user',
              on_enter=[
                  'state_update_program_item', 'check_robot_in',
                  'state_wait_for_user'
              ],
              on_exit=['check_robot_out']),
    ]

    transitions = [
        ('wait_for_user', 'program_run', 'wait_for_user'),
        ('done', 'wait_for_user', 'program_load_instruction'),
        ('error', 'wait_for_user', 'program_error'),
    ]

    state_functions = ['state_wait_for_user']

    def run(self):
        self.fsm.wait_for_user()

    def state_wait_for_user(self, event):
        rospy.logdebug('Current state: state_wait_for_user')

        self.brain.state_manager.update_program_item(
            self.brain.ph.get_program_id(), self.brain.block_id,
            self.brain.instruction)

        rate = rospy.Rate(10)

        while self.brain.user_activity != UserActivity.READY and self.brain.executing_program \
                and not rospy.is_shutdown():
            rate.sleep()

        self.fsm.done(success=True)
Ejemplo n.º 15
0
    def __init__(self):
        """
        Initializes the Model and registers the default state machine transitions 
        available to all models.ctor
        """

        self.state = None
        self._endpoint_service = None
        states = [
            State(n, on_enter='new_state_entered') for n in _transform_states
        ]
        self._machine = Machine(model=self,
                                states=states,
                                initial='started',
                                auto_transitions=False)
        self._machine.add_transition(trigger='fail',
                                     source=list(_transform_states -
                                                 {'terminated'}),
                                     dest='failed')
        self._machine.add_transition(trigger='ready',
                                     source=['started', 'transforming'],
                                     dest='ready')
        self._machine.add_transition(trigger='transform',
                                     source=['started', 'ready'],
                                     dest='transforming',
                                     after='_do_transform')
        self._machine.add_transition(
            trigger='terminate',
            source=list(_transform_states -
                        {'terminating', 'terminated', 'failed'}),
            dest='terminating',
            after='_do_terminate')
        self._machine.add_transition(trigger='terminated',
                                     source='terminating',
                                     dest='terminated')
Ejemplo n.º 16
0
def get_machine(model):
    """Create the parser state machine.

    :param model: An instance of DbtLogParser. The state machine will
        mutate the parser after this function is invoked.
    """
    m = Machine(
        model=model,
        states=[
            State(name=States.SEEK_START),
            State(name=States.SEEK_START_SUMMARY),
            State(name=States.SEEK_FINISH),
            State(name=States.SEEK_DONE),
            State(name=States.DONE),
        ],
        initial=States.SEEK_START,
    )

    # the states above are linear in order; by using `add_ordered_transitions`
    # we automatically make it such that the single trigger `process_next_line`
    # will move linearly between states as ordered above.
    m.add_ordered_transitions(
        trigger="process_next_line",
        # `condition` has a 1:1 mapping with states i.e.
        # we will not transition out of the first state until the first condition
        # is satisfied. conditions correspond to boolean attributes on the model
        # i.e. the parser
        conditions=[
            "found_start",
            "found_start_summary",
            "found_finish",
            "found_done",
            lambda *args, **kwargs: True,
        ],
        # before attempting to transition, the following functions will be
        # invoked with any args or kwargs passed to `process_next_line`;
        # `prepare` occurs before conditions are evaluated;
        # if conditions fail to pass, a transition is halted;
        # in this way, we assure each attempted transition processes another
        # log line
        prepare=[
            "seek_start", "seek_summary", "seek_finish", "seek_done", None
        ],
    )

    return m
 def add_state(self, name, on_enter=None, on_exit=None):
     """
     Append new state to the bot's states list
     See transitions.State class docs for more details.
     """
     args = locals()
     del args['self']
     self.states.append(State(**args))
Ejemplo n.º 18
0
class Bulb(Agent):

    states = [
        State(name='off', on_enter=['set_off']),
        State(name='on', on_enter=['set_on'])
    ]

    def __init__(self, unique_id, model, room):
        super().__init__(unique_id, model)
        self.room = room
        self.machine = Machine(model=self, states=Bulb.states, initial='off')

        self.machine.add_transition('switch_on', '*', 'on')
        self.machine.add_transition('switch_off', '*', 'off')

    def sensorCheck(self):
        userInRoom = self.model.ThereIsUserInRoom(self.room)
        if userInRoom == True:
            if self.state == 'on':
                pass
            else:
                actions = self.model.actionsNear
                if actions['channel'] == 'Bulb' and actions[
                        'action'] == 'SwitchOn':
                    self.switch_on()
        else:
            if self.state == 'off':
                pass
            else:
                actions = self.model.actionsFar
                if actions['channel'] == 'Bulb' and actions[
                        'action'] == 'SwitchOff':
                    self.switch_off()
                else:
                    pass

    def step(self):
        print(self.unique_id, self.state)
        self.sensorCheck()

    def set_off(self):
        pass

    def set_on(self):
        pass
Ejemplo n.º 19
0
    def _load_state(self, state):
        self.logger.debug("Loading state: {}".format(state))
        s = None
        try:
            state_module = load_module('{}.{}.{}'.format(
                self._states_location.replace("/", "."),
                self._state_table_name,
                state
            ))

            # Get the `on_enter` method
            self.logger.debug("Checking {}".format(state_module))

            on_enter_method = getattr(state_module, 'on_enter')
            setattr(self, 'on_enter_{}'.format(state), on_enter_method)
            self.logger.debug(
                "Added `on_enter` method from {} {}".format(
                    state_module, on_enter_method))

            self.logger.debug("Created state")
            s = State(name=state)

            s.add_callback('enter', '_update_status')

            if can_graph:
                s.add_callback('enter', '_update_graph')

            s.add_callback('enter', 'on_enter_{}'.format(state))

        except Exception as e:
            raise error.InvalidConfig("Can't load state modules: {}\t{}".format(state, e))

        return s
Ejemplo n.º 20
0
	def __init__(self, unique_id, model, json, speed = 0.71428):
		super().__init__(unique_id, model)
		"""
		Create a new Occupant object.
			Args: 
				unique_id: Unique identifier corresponding to the agent.
				models: Associated Model object
				json: Json of definition of parameters of behavior
				speed: Movement speed in m/s
			Return: Occupant object
		"""

		self.shape = 'circle' if json.get('shape') == None else json.get('shape')
		self.model.schedule.add(self)
		self.color = 'blue' if json.get('color') == None else json.get('color')
		self.variationSchedule = json.get('variation')
		self.jsonSchedule = json['schedule']
		self.schedule = json['schedule'].copy()
		self.setTodaySchedule()
		self.type = json['type']

		self.markovActivity = json['markovActivity']

		self.timeActivity = json['timeActivity']
		self.timeActivityVariation = json.get('timeActivityVariation')

		self.positionByStateAux = json['states']

		#State machine
		self.positionByState = {}
		self.states = []
		for k, v in json['states'].items():
			name = k
			on_enter = 'start_activity'
			on_exit = 'finish_activity'
			self.states.append(State(name=name, on_enter=[on_enter], on_exit=[on_exit]))
		self.machine = Machine(model=self, states=self.states, initial=list(json['states'].items())[0][0])

		self.triggers = {}
		n_state = 0
		for k, v in json['states'].items():
			name = k
			self.machine.add_transition('setState'+str(n_state), '*', name)
			self.triggers[name] = 'setState'+str(n_state)+'()'
			n_state = n_state + 1

		self.markov_machine = Markov(self)

		self.speed = speed
		self.markov = True
		self.time_activity = 0
		self.lastSchedule = 0.0
		self.N = 0
		self.pos = (0, 0)
		self.pos_to_go = (0, 0)
		self.movements = [self.pos]
		self.inbuilding = False
Ejemplo n.º 21
0
 def createNewState(self, textStr):
     self.statesCounter = self.getNextStateId()
     logger.debug("Created state " +
                  self.convertStateIdToName(self.statesCounter))
     self.machine.add_states(
         State(name=self.convertStateIdToName(self.statesCounter)))
     self.stateIdToContent[self.convertStateIdToName(
         self.statesCounter)] = textStr
     return self.statesCounter
Ejemplo n.º 22
0
    def _init_state_machine(self):
        states = [
            State(name='Init', on_exit=['_save_state']),
            State(name='first_timestamp', on_exit=['_save_state']),
            State(name='timestamp', on_exit=['_save_state']),
            State(name='running', on_exit=['_save_state']),
            State(name='walking', on_exit=['_save_state']),
            State(name='running', on_exit=['_save_state']),
            State(name='distance', on_exit=['_save_state']),
            State(name='steps', on_exit=['_save_state'])
        ]

        self.machine = Machine(model=self, states=states, initial='Init')

        self.machine.add_transition('run',
                                    'Init',
                                    'first_timestamp',
                                    conditions=['_is_first_timestamp'])
        self.machine.add_transition('run',
                                    'first_timestamp',
                                    'timestamp',
                                    conditions=['_is_timestamp'])
        self.machine.add_transition('run',
                                    '*',
                                    'timestamp',
                                    conditions=['_is_timestamp'])
        self.machine.add_transition('run',
                                    'timestamp',
                                    'running',
                                    conditions=['_is_running'])
        self.machine.add_transition('run',
                                    'timestamp',
                                    'walking',
                                    conditions=['_is_walking'])
        self.machine.add_transition('run',
                                    'walking',
                                    'steps',
                                    conditions=['_is_step'])
        self.machine.add_transition('run',
                                    'walking',
                                    'distance',
                                    conditions=['_is_distance'])
        self.machine.add_transition('run',
                                    'running',
                                    'steps',
                                    conditions=['_is_step'])
        self.machine.add_transition('run',
                                    'running',
                                    'distance',
                                    conditions=['_is_distance'])

        self.machine.on_enter_distance(self._handle_distance)
        self.machine.on_enter_steps(self._handle_steps)
Ejemplo n.º 23
0
 def machine(self):
     if self._machine is None:
         self._initial = State(name='machine_initial')
         self._machine = CustomStateMachine(model=self,
                                            initial=self._initial,
                                            auto_transitions=False,
                                            show_conditions=True,
                                            show_auto_transitions=True,
                                            show_state_attributes=True)
     return self._machine
Ejemplo n.º 24
0
class DummyFSM(BrainFSM):
    states = [
        State(name='dummy',
              on_enter=['state_update_program_item', 'state_dummy']),
        State(name='learning_dummy',
              on_enter=['learning_load_block_id', 'state_learning_dummy']),
        State(name='learning_dummy_run',
              on_enter=['learning_load_block_id', 'state_learning_dummy_run']),
    ]

    transitions = [('dummy', 'program_run', 'dummy'),
                   ('done', 'dummy', 'program_load_instruction'),
                   ('error', 'dummy', 'program_error'),
                   ('dummy', 'learning_run', 'learning_dummy'),
                   ('done', 'learning_dummy', 'learning_step_done'),
                   ('error', 'learning_dummy', 'learning_step_error'),
                   ('dummy_run', 'learning_run', 'learning_dummy_run'),
                   ('done', 'learning_dummy_run', 'learning_run'),
                   ('error', 'learning_dummy_run', 'learning_step_error')]

    state_functions = [
        'state_dummy', 'state_learning_dummy', 'state_learning_dummy_run'
    ]

    def run(self):
        self.fsm.dummy()

    def learning(self):
        self.fsm.dummy()

    def learning_run(self):
        self.fsm.dummy_run()

    def state_dummy(self, event):
        rospy.logdebug('Current state: state_dummy')
        self.fsm.done(success=True)

    def state_learning_dummy(self, event):
        rospy.logdebug('Current state: state_dummy_points')

    def state_learning_dummy_run(self, event):
        rospy.logdebug('Current state: state_learning_dummy_run')
        self.fsm.done(success=True)
class TestFSM(object):

    states = [
        State('r', on_enter='set_red'),
        State('g', on_enter='set_green'),
        State('b', on_enter='set_blue')
    ]

    def __init__(self, device_group):
        self.device_group = device_group

        self.machine = Machine(self, states=TestFSM.states, initial='r')

        self.machine.add_transition(
            trigger='switch',
            source='r',
            dest='g'
        )

        self.machine.add_transition(
            trigger='switch',
            source='g',
            dest='b'
        )

        self.machine.add_transition(
            trigger='switch',
            source='b',
            dest='r'
        )

    def set_red(self):
        self.device_group.send_message(4, 0, 3, b'\xff\x00\x00')

    def set_green(self):
        self.device_group.send_message(4, 0, 3, b'\x00\xff\x00')

    def set_blue(self):
        self.device_group.send_message(4, 0, 3, b'\x00\x00\xff')

    def handle_message(self, msg):
        if msg[0] == 4 and msg[2] == 4 and msg[3] == '\x01':
            self.switch()
Ejemplo n.º 26
0
def deserialize_transitions(data: dict) -> Dict[Binding, Transition]:
    transitions_by_binding = {}
    for binding in Binding:
        transition = data.get(binding.value, None)
        if transition is None:
            continue
        transitions_by_binding[binding] = Transition(
            starting_fidl=State(transition[0]['fidl']),
            starting_src=from_src_filename(transition[0]['source']),
            changes=tuple(deserialize_change(c) for c in transition[1:]))
    return transitions_by_binding
    def __init__(self, *a, **k):
        # type: (Any, Any) -> None
        transitions = [
            ["start", SequenceState.UN_STARTED, SequenceState.STARTED],
            ["terminate", SequenceState.STARTED, SequenceState.TERMINATED],
            ["cancel", SequenceState.STARTED, SequenceState.CANCELLED],
            ["error", SequenceState.STARTED, SequenceState.ERRORED],
        ]

        states = [
            State(SequenceState.UN_STARTED),
            State(SequenceState.STARTED, on_enter=[self._on_start]),
            State(SequenceState.TERMINATED, on_enter=[self._on_terminate]),
            State(SequenceState.CANCELLED, on_enter=[self._on_cancel]),
            State(SequenceState.ERRORED, on_enter=[self._on_terminate]),
        ]

        self._state_machine = Machine(states=states,
                                      transitions=transitions,
                                      initial=SequenceState.UN_STARTED)
Ejemplo n.º 28
0
async def run(robot: cozmo.robot.Robot):
	robot.camera.image_stream_enabled = True
	await robot.set_head_angle(cozmo.util.degrees(7)).wait_for_completed()

	states = [	State(name = 'Searching', on_enter=[], on_exit=[]),
				State(name = 'PickCube', on_enter=[], on_exit=[]),
				State(name = 'DropCube', on_enter=[], on_exit=[]),
				State(name = 'WrongArea', on_enter=[], on_exit=[]),]

	transitions = [	{'trigger':'safeZone','source':'WrongArea','dest':'Searching'},
					{'trigger':'foundCube','source':'Searching','dest':'PickCube'},
					{'trigger':'deliverCube','source':'PickCube','dest':'DropCube'},
					{'trigger':'findPos','source':'DropCube','dest':'WrongArea'},
					{'trigger':'oops','source':'Searching','dest':'WrongArea'},] #this last trigger is mostly optional

	initState = 'WrongArea'
	machine = Machine(model=robot, states=states, transitions=transitions, initial=initState, ignore_invalid_triggers=True)
	while(True):
		cozmo.robot.Robot.drive_off_charger_on_connect = False
		robot = await switch[robot.state](robot);
Ejemplo n.º 29
0
    def __init__(self):
        self.position_subscriber = rospy.Subscriber("/ground_truth_to_tf/pose", PoseStamped, self.callback_position)
        self.vector_publisher = rospy.Publisher("/vector", Vector3, queue_size=10)
        rospy.loginfo("hello")
        self.states = [
            State(name="plane_centering", on_enter=['state_plane_centering']),
            State(name="cone_drop", on_enter=['state_cone_drop']),
            State(name="height_hit", on_enter=['state_height_hit']),
            State(name="landed", on_enter=['state_landed']),
            State(name="post_landed")
        ]

        self.vc = Vector_Control()
        self.machine = Machine(model=self.vc, states=self.states, initial='plane_centering')

        self.machine.add_transition("next", "plane_centering", "cone_drop", conditions="is_centered")
        self.machine.add_transition("next", "cone_drop", "height_hit", conditions="is_out_of_the_cone")
        self.machine.add_transition("next", "height_hit", "plane_centering", conditions="is_height_hit")
        self.machine.add_transition("next", "cone_drop", "landed", conditions="is_landing")
        self.machine.add_transition("next", "landed", "post_landed")
        self.machine.add_transition("next", "post_landed", "post_landed")
Ejemplo n.º 30
0
 def test_auto_transitions(self):
     states = ['A', {'name': 'B'}, State(name='C')]
     m = Machine(None, states, initial='A', auto_transitions=True)
     m.to_B()
     self.assertEquals(m.state, 'B')
     m.to_C()
     self.assertEquals(m.state, 'C')
     m.to_A()
     self.assertEquals(m.state, 'A')
     # Should fail if auto transitions is off...
     m = Machine(None, states, initial='A', auto_transitions=False)
     with self.assertRaises(TypeError):
         m.to_C()
Ejemplo n.º 31
0
    def __init__(self):
        #the IR laser is connected to 'laser2'
        self._laser_conf = rospy.Publisher(
            '/flymad_micro/laser2/configuration',
            flymad.msg.LaserConfiguration,
            latch=True)  #latched so message is guarenteed to arrive
        #configure the laser
        self._laser_conf.publish(
            enable=
            True,  #always enabled, we turn it on/off using /experiment/laser
            frequency=0,  #constant (not pulsed)
            intensity=1.0)  #full power

        #ensure the targeter is running so we can control the laser
        rospy.loginfo('waiting for targeter')
        rospy.wait_for_service('/experiment/laser')
        self._laser = rospy.ServiceProxy('/experiment/laser',
                                         flymad.srv.LaserState)
        self._laser(LASERS_ALL_OFF)

        self._flyx, self._flyy = 0, 0
        #the position of the currently targeted object is sent by the targeter. In the
        #case of a single fly, the default behaviour of the targeter is to target the
        #one and only fly. If there are multiple flies you neet to instruct the targeter
        #which fly to target. The requires you recieve the raw position of all tracked
        #objects, /flymad/tracked, and decide which one is interesting by sending
        #/flymad/target_object with.
        _ = rospy.Subscriber('/targeter/targeted', flymad.msg.TargetedObj,
                             self.on_targeted)

        self._pubpts = rospy.Publisher('/draw_geom/poly',
                                       geometry_msgs.msg.Polygon,
                                       latch=True)

        #set up the states of this experiment
        s1 = State('laser_on', on_enter=['on_enter_laser_on'])
        s2 = State('laser_off', on_enter=['on_enter_laser_off'])
        s3 = State('tile', on_enter=['on_enter_tile'])
        self._machine = OrderedStateMachine(self, states=[s1, s2, s3])
Ejemplo n.º 32
0
    def _load_state(self, state):
        self.logger.debug("Loading state: {}".format(state))
        try:
            state_module = load_module('pocs.state.states.{}.{}'.format(self._state_table_name, state))
            s = None

            # Get the `on_enter` method
            self.logger.debug("Checking {}".format(state_module))
            if hasattr(state_module, 'on_enter'):
                on_enter_method = getattr(state_module, 'on_enter')
                setattr(self, 'on_enter_{}'.format(state), on_enter_method)
                self.logger.debug("Added `on_enter` method from {} {}".format(state_module, on_enter_method))

                self.logger.debug("Created state")
                s = State(name=state)

                s.add_callback('enter', '_update_graph')
                s.add_callback('enter', '_update_status')
                s.add_callback('enter', 'on_enter_{}'.format(state))

        except Exception as e:
            self.logger.warning("Can't load state modules: {}\t{}".format(state, e))

        return s