Пример #1
0
    def build(self, **actions):
        """Construct an FSM from a parsed fsm description file.

            Keyword arguments:
            **actions -- each action routine callable
        """
        states = {}
        for state in self.states.values():
            s = FSM.STATE(
                name=state.name,
                on_enter=actions[state.enter] if state.enter else None,
                on_exit=actions[state.exit] if state.exit else None,
            )
            states[s.name] = s
            for event in state.events.values():
                e = FSM.EVENT(
                    name=event.name,
                    actions=[actions[n] for n in event.actions],
                    next_state=event.next_state,
                )
                s.events[e.name] = e
        for state in states.values():
            for event in state.events.values():
                if event.next_state:
                    event.next_state = states[event.next_state]
        fsm = FSM.FSM(states.values())
        fsm.state = self.first_state
        fsm.context = self.context
        fsm.exception = self.exception
        return fsm
Пример #2
0
def dangie_fsm(functions):
    from fsm import FSM
    fsm = FSM()
    for function in functions:
        fsm = function.add_to_fsm(fsm)
    fsm = fsm.make_dangie_ready()
    return fsm
Пример #3
0
    def __init__(self, game_opts):
        # part of the borg pattern
        self.__dict__ = self.__shared_state

        ## the game scenes/levels
        self.scenes = FSM()

        # initialise a sample level
        # TODO: find a way of applying lazy initialisation
        # on level creation - a level should be created only
        # right before executed
        # flev = LevelFactory().create_level(
        #     constants.SCENES['level_one'],
        #     game_opts)
        flev = LevelFactory().create_level(constants.SCENES['level_one'])

        # set and group the scenes
        scenes = (Intro(game_opts), Menu(game_opts), flev)

        # add the scenes to the state machine
        for s in scenes:
            self.scenes.add_state(s)

        # enable the default state
        self.scenes.active_state = scenes[0]
Пример #4
0
def test_oblivion_crawl(a):
    # When crawling a new FSM, we should avoid generating an oblivion state.
    # `abc` has no oblivion state... all the results should not as well!
    abc = FSM(alphabet={"a", "b", "c"},
              states={0, 1, 2, 3},
              initial=0,
              accepting={3},
              transition={
                  0: {
                      "a": 1
                  },
                  1: {
                      "b": 2
                  },
                  2: {
                      "c": 3
                  },
              })
    assert len((abc + abc).states) == 7
    assert len(abc.star().reduce().states) == 3
    assert len((abc * 3).states) == 10
    assert len(reversed(abc).states) == 4
    assert len((abc | abc).states) == 4
    assert len((abc & abc).states) == 4
    assert len((abc ^ abc).reduce().states) == 1
    assert len((abc - abc).reduce().states) == 1
Пример #5
0
def test_invalid_fsms():
    # initial state 1 is not a state
    try:
        FSM(alphabet={}, states={}, initial=1, accepting=set(), transition={})
        assert False
    except AssertionError:
        assert False
    except Exception:
        pass

    # final state 2 not a state
    try:
        FSM(alphabet={}, states={1}, initial=1, accepting={2}, transition={})
        assert False
    except AssertionError:
        assert False
    except Exception:
        pass

    # invalid transition for state 1, symbol "a"
    try:
        FSM(alphabet={"a"},
            states={1},
            initial=1,
            accepting=set(),
            transition={1: {
                "a": 2
            }})
        assert False
    except AssertionError:
        assert False
    except Exception:
        pass
Пример #6
0
def test_star_advanced():
    # This is (a*ba)*. Naively connecting the final states to the initial state
    # gives the incorrect result here.
    starred = FSM(alphabet={"a", "b"},
                  states={0, 1, 2, "oblivion"},
                  initial=0,
                  accepting={2},
                  transition={
                      0: {
                          "a": 0,
                          "b": 1
                      },
                      1: {
                          "a": 2,
                          "b": "oblivion"
                      },
                      2: {
                          "a": "oblivion",
                          "b": "oblivion"
                      },
                      "oblivion": {
                          "a": "oblivion",
                          "b": "oblivion"
                      },
                  }).star()
    assert starred.alphabet == frozenset(["a", "b"])
    assert starred.accepts("")
    assert not starred.accepts("a")
    assert not starred.accepts("b")
    assert not starred.accepts("aa")
    assert starred.accepts("ba")
    assert starred.accepts("aba")
    assert starred.accepts("aaba")
    assert not starred.accepts("aabb")
    assert starred.accepts("abababa")
Пример #7
0
 def __init__(self, threaded = False):
     if threaded:
         FSMThreaded.__init__(self, FSM1) 
         self.eventRoutine = getattr(self, 'SendEvent')
     else:
         FSM.__init__(self, FSM1) 
         self.eventRoutine = getattr(self, 'OnEvent')
Пример #8
0
def test_alphabet_unions():
    # Thanks to sparse transitions it should now be possible to compute the union of FSMs
    # with disagreeing alphabets!
    a = FSM(
        alphabet={"a"},
        states={0, 1},
        initial=0,
        accepting={1},
        transition={
            0: {
                "a": 1
            },
        },
    )

    b = FSM(
        alphabet={"b"},
        states={0, 1},
        initial=0,
        accepting={1},
        transition={
            0: {
                "b": 1
            },
        },
    )

    assert (a | b).accepts(["a"])
    assert (a | b).accepts(["b"])
    assert (a & b).empty()
    assert (a + b).accepts(["a", "b"])
    assert (a ^ b).accepts(["a"])
    assert (a ^ b).accepts(["b"])
Пример #9
0
 def __init__(self, name="tun/tap client", options=None, \
              initstate=None, verbose=None, **kwargs):
     if options is None: options = tunclient_defaults
     self.__clientretry = 0
     self.__options = options
     self.__sock = None
     initstate = self.CONNECT
     FSM.__init__(self, name=name, initstate=initstate, \
                  verbose=options.verbose, **kwargs)
Пример #10
0
    def test_sl_to_fsm_2(self):
        """ Checks if a 2-SL grammar translates to FSM correctly. """
        f = FSM(initial=">", final="<")
        grammar = [(">", "a"), ("b", "a"), ("a", "b"), ("b", "<")]
        f.sl_to_fsm(grammar)

        tr = {((">", ), "a", ("a", )), (("b", ), "a", ("a", )),
              (("a", ), "b", ("b", )), (("b", ), "<", ("<", ))}
        self.assertTrue(set(f.transitions) == tr)
Пример #11
0
    def test_accepts_noStates(self):
        f = FSM()
        # testing accepts without given a startstate
        self.assertRaises(ValueError,f.accepts,'10121')

        # given non-existent states
        f.setstartstate("pie")
        self.assertRaises(KeyError,f.addtransition,'fail','this','1')
        self.assertFalse(f.accepts("thereisnothing"))
Пример #12
0
 def test_trim_fsm_2(self):
     f = FSM(initial=">", final="<")
     f.transitions = [((">", ), "a", ("a", )), (("b", ), "a", ("a", )),
                      (("a", ), "b", ("b", )), (("b", ), "<", ("<", )),
                      ((">", ), "c", ("c", )), (("d", ), "<", ("<", ))]
     goal = {((">", ), "a", ("a", )), (("b", ), "a", ("a", )),
             (("a", ), "b", ("b", )), (("b", ), "<", ("<", ))}
     f.trim_fsm()
     self.assertTrue(set(f.transitions) == goal)
Пример #13
0
    def test_setacceptstate(self):
        f = FSM()
        f.addstate('freshman')
        f.setacceptstate('freshman')
        assert('freshman' in f.acceptStates)

        # labeling non-existant state as an accept state
        f = FSM()
        f.addstate('sophmore')
        self.assertRaises(ValueError,f.setacceptstate,'freshman')
Пример #14
0
    def __init__(self):
        # part of the borg pattern
        self.__dict__ = self.__shared_state

        # initialize the state
        State.__init__(self, constants.SCENES['level_one'])
        # the 1st level states
        self.states = FSM()
        # self.game_opts = game_opts
        self.states.active_state = None
Пример #15
0
def create_new_fsm():
    f = FSM("INIT", [])
    f.set_default_transition(do_default, "INIT")
    f.add_transition("START", "INIT", do_start, "RUNNING")
    f.add_transition("STOP", "RUNNING", do_start, "INIT")
    f.add_transition_list(["START", "INIT", "RELOAD", "RESTART"], "RUNNING", running_ok, "RUNNING")
    return f
Пример #16
0
def test_new_set_methods(a, b):
    # A whole bunch of new methods were added to the FSM module to enable FSMs to
    # function exactly as if they were sets of strings (symbol lists), see:
    # https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset
    # But do they work?
    assert len(a) == 1
    assert len((a | b) * 4) == 16
    try:
        len(a.star())
        assert False
    except OverflowError:
        pass

    # "in"
    assert "a" in a
    assert not "a" in b
    assert "a" not in b

    # List comprehension!
    four = (a | b) * 2
    for string in four:
        assert string == ["a", "a"]
        break
    assert [s for s in four] == [["a", "a"], ["a", "b"], ["b", "a"],
                                 ["b", "b"]]

    # set.union() imitation
    assert FSM.union(a, b) == a.union(b)
    assert len(FSM.union()) == 0
    assert FSM.intersection(a, b) == a.intersection(b)

    # This takes a little explaining. In general, `a & b & c` is equivalent to
    # `EVERYTHING & a & b & c` where `EVERYTHING` is an FSM accepting every
    # possible string. Similarly `a` is equivalent to `EVERYTHING & a`, and the
    # intersection of no sets at all is... `EVERYTHING`.
    # However, since we compute the union of alphabets, and there are no
    # alphabets, the union is the empty set. So the only string which `EVERYTHING`
    # actually recognises is the empty string, [] (or "" if you prefer).
    int_none = FSM.intersection()
    assert len(int_none) == 1
    assert [] in int_none

    assert (a | b).difference(a) == FSM.difference(
        (a | b), a) == (a | b) - a == b
    assert (a | b).difference(a, b) == FSM.difference(
        (a | b), a, b) == (a | b) - a - b == null("ab")
    assert a.symmetric_difference(b) == FSM.symmetric_difference(a, b) == a ^ b
    assert a.isdisjoint(b)
    assert a <= (a | b)
    assert a < (a | b)
    assert a != (a | b)
    assert (a | b) > a
    assert (a | b) >= a

    assert list(a.concatenate(a, a).strings()) == [["a", "a", "a"]]
    assert list(a.concatenate().strings()) == [["a"]]
    assert list(FSM.concatenate(b, a, b).strings()) == [["b", "a", "b"]]
    assert list(FSM.concatenate().strings()) == []
    assert not a.copy() is a
Пример #17
0
def test_unspecified_acceptance():
    a = FSM(
        alphabet={"a", "b", "c", unspecified},
        states={1},
        initial=1,
        accepting={1},
        transition={1: {
            "a": 1,
            "b": 1,
            "c": 1,
            unspecified: 1
        }},
    )
    assert a.accepts("d")
Пример #18
0
def test_empty(a, b):
    assert not a.empty()
    assert not b.empty()

    assert FSM(
        alphabet={},
        states={0, 1},
        initial=0,
        accepting={1},
        transition={
            0: {},
            1: {}
        },
    ).empty()

    assert not FSM(
        alphabet={},
        states={0},
        initial=0,
        accepting={0},
        transition={
            0: {}
        },
    ).empty()

    assert FSM(
        alphabet={"a", "b"},
        states={0, 1, None, 2},
        initial=0,
        accepting={2},
        transition={
            0: {
                "a": 1,
                "b": 1
            },
            1: {
                "a": None,
                "b": None
            },
            None: {
                "a": None,
                "b": None
            },
            2: {
                "a": None,
                "b": None
            },
        },
    ).empty()
Пример #19
0
    def get_fsm(self, sample_id):
        """
        Return a FSM representation taking in consideration 1-gram sequence
        """
        fsm = FSM()

        for thread_id, total in self.get_stats_for(sample_id):
            sfrom = 'start'

            for num, caller in self.foreach_syscall(sample_id, thread_id):
                fsm.add(sfrom, num, num)
                sfrom = num

        fsm.start('start')
        return fsm
Пример #20
0
class LevelOneFactory(State):
    # part of the borg pattern
    __shared_state = {}

    # def __init__(self, game_opts):
    def __init__(self):
        # part of the borg pattern
        self.__dict__ = self.__shared_state

        # initialize the state
        State.__init__(self, constants.SCENES['level_one'])
        # the 1st level states
        self.states = FSM()
        # self.game_opts = game_opts
        self.states.active_state = None

    # rooms, doors, obstacles, etc.
    def create_level(self):
        print('creating level 1')

        # set and group the rooms
        r1 = self.create_room('office')
        r2 = self.create_room('park')
        level = (r1, r2)

        # add the rooms to the state machine
        for r in level:
            self.states.add_state(r)

        # enable the default state
        self.states.active_state = level[0]

        return self.states

    def run(self):
        self.states.run()

    def create_room(self, name):
        return Room(name)

    def create_door(self, colour):
        return Door(colour)

    ## what to do when the level is enabled
    #
    # @param self the object pointer
    def do_actions(self):
        safe_exit()
Пример #21
0
class LevelOneFactory(State):
    # part of the borg pattern
    __shared_state = {}

    # def __init__(self, game_opts):
    def __init__(self):
        # part of the borg pattern
        self.__dict__ = self.__shared_state

        # initialize the state
        State.__init__(self, constants.SCENES['level_one'])
        # the 1st level states
        self.states = FSM()
        # self.game_opts = game_opts
        self.states.active_state = None

    # rooms, doors, obstacles, etc.
    def create_level(self):
        print('creating level 1')

        # set and group the rooms
        r1 = self.create_room('office')
        r2 = self.create_room('park')
        level = (r1, r2)

        # add the rooms to the state machine
        for r in level:
            self.states.add_state(r)

        # enable the default state
        self.states.active_state = level[0]

        return self.states

    def run(self):
        self.states.run()
        
    def create_room(self, name):
        return Room(name)

    def create_door(self, colour):
        return Door(colour)

    ## what to do when the level is enabled
    #
    # @param self the object pointer
    def do_actions(self):
        safe_exit()
Пример #22
0
def main():
    try:
        state_machine = FSM()
        state_machine.start()

    except KeyboardInterrupt:
        log.debug('User ended the program')

    except Exception as e:
        var = traceback.format_exc()
        log.debug(e)
        log.debug(str(var))

    finally:
        GPIO.cleanup()
        log.debug('Main Cleaned Up')
Пример #23
0
    def test_scan_sl_2(self):
        """ Checks if a FSM for 2-SL grammar can correctly
            recognize strings.
        """
        f = FSM(initial=">", final="<")
        f.transitions = [((">", ), "a", ("a", )), (("b", ), "a", ("a", )),
                         (("a", ), "b", ("b", )), (("b", ), "<", ("<", ))]

        self.assertTrue(f.scan_sl(">abab<"))
        self.assertTrue(f.scan_sl(">ab<"))
        self.assertTrue(f.scan_sl(">abababab<"))

        self.assertFalse(f.scan_sl("><"))
        self.assertFalse(f.scan_sl(">a<"))
        self.assertFalse(f.scan_sl(">ba<"))
        self.assertFalse(f.scan_sl(">ababbab<"))
Пример #24
0
 def test_trim_fsm_3(self):
     f = FSM(initial=">", final="<")
     f.transitions = [((">", "a"), "b", ("a", "b")),
                      (("a", "b"), "a", ("b", "a")),
                      (("b", "a"), "b", ("a", "b")),
                      (("a", "b"), "<", ("b", "<")),
                      ((">", ">"), "a", (">", "a")),
                      (("b", "<"), "<", ("<", "<")),
                      ((">", "b"), "j", ("b", "j")),
                      ((">", ">"), "j", (">", "j")),
                      (("j", "k"), "o", ("k", "o"))]
     goal = {((">", "a"), "b", ("a", "b")), (("a", "b"), "a", ("b", "a")),
             (("b", "a"), "b", ("a", "b")), (("a", "b"), "<", ("b", "<")),
             ((">", ">"), "a", (">", "a")), (("b", "<"), "<", ("<", "<"))}
     f.trim_fsm()
     self.assertTrue(set(f.transitions) == goal)
Пример #25
0
async def game(ctx):
    await _join(ctx)
    channel = ctx.message.guild.voice_client.channel
    await asyncio.gather(
        set_mute_all(channel.members, mute=False),
        ctx.message.channel.send('Starting game in {}'.format(channel.name)),
        client.change_presence(activity=discord.Game(name='Among Us')),
    )

    vision = Vision(static_templates, monitor)
    fsm = FSM(
        on_change_state={
            'playing':
            lambda: asyncio.run_coroutine_threadsafe(
                set_mute_all(channel.members), main_loop),
            'voting':
            lambda: asyncio.run_coroutine_threadsafe(
                set_mute_all(channel.members, mute=False), main_loop)
        })
    controller = Controller(fsm, vision)

    async def step():
        controller.step()
        if not should_stop:
            await asyncio.sleep(1)
            await step()

    global should_stop
    should_stop = False
    await step()
Пример #26
0
 def test_constuctor(self):
     f = FSM()
     assert(type(f) == FSM)
     assert(f.currentState is None)
     assert(len(f.acceptStates) == 0)
     assert(f.startState is None)
     assert(len(f.states) == 0)
Пример #27
0
def test_crawl_reduction():
    # this is "0*1" in heavy disguise. crawl should resolve this duplication
    # Notice how states 2 and 3 behave identically. When resolved together,
    # states 1 and 2&3 also behave identically, so they, too should be resolved
    # (this is impossible to spot before 2 and 3 have been combined).
    # Finally, the oblivion state should be omitted.
    merged = FSM(alphabet={"0", "1"},
                 states={1, 2, 3, 4, "oblivion"},
                 initial=1,
                 accepting={4},
                 transition={
                     1: {
                         "0": 2,
                         "1": 4
                     },
                     2: {
                         "0": 3,
                         "1": 4
                     },
                     3: {
                         "0": 3,
                         "1": 4
                     },
                     4: {
                         "0": "oblivion",
                         "1": "oblivion"
                     },
                     "oblivion": {
                         "0": "oblivion",
                         "1": "oblivion"
                     },
                 }).reduce()
    assert len(merged.states) == 2
Пример #28
0
def test_difference(a, b):
    aorb = FSM(
        alphabet={"a", "b"},
        states={0, 1, None},
        initial=0,
        accepting={1},
        transition={
            0: {
                "a": 1,
                "b": 1
            },
            1: {
                "a": None,
                "b": None
            },
            None: {
                "a": None,
                "b": None
            },
        },
    )

    assert list((a ^ a).strings()) == []
    assert list((b ^ b).strings()) == []
    assert list((a ^ b).strings()) == [["a"], ["b"]]
    assert list((aorb ^ a).strings()) == [["b"]]
Пример #29
0
 def test_addstate(self):
     a = FSM()
     a.addstate('q1')
     a.addstate('q2')
     a.addstate('q3')
     a.addstate('q4')
     a.addstate('q5')
     a.addstate('q6')
     assert(len(a.states) == 6)
Пример #30
0
def parse_inventory(file):
    fsm = FSM(_S, _S.TOP, [_S.TOP], machine)
    fsm.reset()
    fsm.data = {'current_item': {}, 'relic': [], 'morality': [], 'archeo': []}
    #fsm.tracing(True)

    fsm.parse(file)
    return fsm.data['relic'], fsm.data['archeo'], fsm.data['morality']
Пример #31
0
    def __init__(self):
        # part of the borg pattern
        self.__dict__ = self.__shared_state

        # initialize the state
        State.__init__(self, constants.SCENES['level_one'])
        # the 1st level states
        self.states = FSM()
        # self.game_opts = game_opts
        self.states.active_state = None
Пример #32
0
class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.fsm = FSM(CONNECTION_STATES, start='LISTENING')

    def test_connect_accept_close(self):
        assert self.fsm.get_state_by_events(
            ['connect', 'accept', 'read', 'close']) == 'CLOSED'

    def test_read_before_connect_raise_error(self):
        assert self.fsm.get_state_by_events(
            ['read', 'connect', 'accept', 'read', 'close']) == 'ERROR'

    def test_read_read_read(self):
        assert self.fsm.get_state_by_events(
            ['connect', 'accept', 'read', 'read', 'read']) == 'READING'

    def test_write_write_write(self):
        assert self.fsm.get_state_by_events(
            ['connect', 'accept', 'write', 'write', 'write']) == 'WRITING'
Пример #33
0
    def __init__(self):
        # Create a State Machine object
        self.__my_fsm = FSM()

        # Create a Sender and Receiver Driver object
        self.__sd = Sender_Driver(self.__my_fsm)
        self.__rd = Receiver_Driver(self.__my_fsm)

        # Create a GUI object
        self.__my_gui = SerialGUI(self.__my_fsm, self.__sd, self.__rd)
        self.__my_gui.window.mainloop()
Пример #34
0
def test_reduce():
    # FSM accepts no strings but has 3 states, needs only 1
    asdf = FSM(
        alphabet={None},
        states={0, 1, 2},
        initial=0,
        accepting={1},
        transition={
            0: {
                None: 2
            },
            1: {
                None: 2
            },
            2: {
                None: 2
            },
        },
    )
    asdf = asdf.reduce()
    assert len(asdf.states) == 1
Пример #35
0
 def main(self):
     """ Main program method """
     # $ - numbers [0-9]
     # ¤ - LED IDs [0-5]
     # @ - any character
     rules = [
         Rule("init", "read", "@", "A1"),
         Rule("read", "read", "$", "A2"),
         Rule("read", "verify", "*", "A3"),
         Rule("read", "init", "@", "A4"),
         Rule("verify", "active", "Y", "A5"),
         Rule("verify", "init", "N"),
         Rule("active", "read-2", "*"),
         Rule("active", "duration-entry", "¤",
              "A9"),  # WARNING: only 0-5 work, 6-9 crash
         Rule("active", "logout", "#"),
         Rule("read-2", "read-2", "$", "A2"),
         Rule("read-2", "read-3", "*", "A7"),
         Rule("read-2", "active", "@", "A6"),
         Rule("read-3", "read-3", "$", "A2"),
         Rule("read-3", "active", "*", "A8"),
         Rule("read-3", "active", "@", "A6"),
         Rule("duration-entry", "duration-entry", "$", "A10"),
         Rule("duration-entry", "active", "*", "A11"),
         Rule("logout", "init", "#", "A12"),
         Rule("logout", "active", "@"),
     ]
     fsm = FSM()
     fsm.set_rules(rules)
     fsm.run()
Пример #36
0
    def __init__(self):
        self.FSM = FSM(self)

        # States
        self.FSM.addState("Sleep", Sleep(self.FSM))
        self.FSM.addState("Walk", Walk(self.FSM))
        self.FSM.addState("Meow", Meow(self.FSM))

        # Transitions
        self.FSM.addTransition("toSleep", ToSleep("Sleep"))
        self.FSM.addTransition("toWalk", ToWalk("Walk"))
        self.FSM.addTransition("toMeow", ToMeow("Meow"))

        self.FSM.setState("Sleep")
Пример #37
0
    def __init__(self, name="tun/tap server", options=None, \
                 initstate=None, verbose=None, **kwargs):
        """
        Constructor.

        :param name:      Name of server.
        :param options:   Configuration options (see `tunserver_defaults`).
        :param initstate: Ignored by TunServer.
        :param verbose:   Passed to `FSM` constructor.
        :param kwargs:    Paseed to `FSM` constructor.
        """
        if options is None: options = tunserver_defaults
        self.verbose   = options.verbose
        self.__options = options
        self.__tun = None
        self.__recv = None
        self.__sock = None
        self.__conn = None
        self.__client = None
        # call FSM constructor
        initstate = self.CONFIG
        FSM.__init__(self, name=name, initstate=initstate, \
                           verbose=self.verbose, **kwargs)
Пример #38
0
    def __init__(self, game_opts):
        ## the game scenes/levels
        self.scenes = FSM()

        # set the scenes
        intro_state = Intro(game_opts)
        menu_state = Menu(game_opts)

        # group the scenes
        scenes = (intro_state, menu_state)

        # add the scenes to the state machine
        for s in scenes:
            self.scenes.add_state(s)
        
        # enable the active state
        self.scenes.active_state = intro_state
Пример #39
0
class GameManager(object):

    ## initialize the game manager
    #
    # @param self the object pointer
    # @param game_opts the game's command line options
    def __init__(self, game_opts):
        ## the game scenes/levels
        self.scenes = FSM()

        # set the scenes
        intro_state = Intro(game_opts)
        menu_state = Menu(game_opts)

        # group the scenes
        scenes = (intro_state, menu_state)

        # add the scenes to the state machine
        for s in scenes:
            self.scenes.add_state(s)
        
        # enable the active state
        self.scenes.active_state = intro_state

    ## execute the appropriate scene
    #
    # @param self the object pointer
    def run_scene(self):
        self.scenes.run()

    ## change (and start) the active scene
    #
    # @param self the object pointer
    # @param scene the name of the new active scene
    def set_active_scene(self, scene):
        self.scenes.set_state(scene)
        self.run_scene()
Пример #40
0
 def __init__(self):
     FSM.__init__(self, OutContext())
Пример #41
0
	def __init__(self):
		FSM.__init__(self)
Пример #42
0
class UICoreRos(UICore):

    """The class builds on top of UICore and adds ROS-related stuff and application logic.

    Attributes:
        user_status (UserStatus): current user tracking status
        fsm (FSM): state machine maintaining current state of the interface and proper transitions between states
        state_manager (interface_state_manager): synchronization of interfaces within the ARTable system
        scene_pub (rospy.Publisher): publisher for scene images
        last_scene_update (rospy.Time): time when the last scene image was published
        scene_img_deq (Queue.Queue): thread-safe queue for scene images (which are published in separate thread)
        projectors (list): array of ProjectorHelper instances
        art (ArtApiHelper): easy access to ARTable services

    """

    def __init__(self):

        origin = rospy.get_param("~scene_origin", [0, 0])
        size = rospy.get_param("~scene_size", [1.2, 0.75])
        rpm = rospy.get_param("~rpm", 1280)

        super(UICoreRos, self).__init__(origin[0], origin[1], size[0], size[1], rpm)

        QtCore.QObject.connect(self, QtCore.SIGNAL('objects'), self.object_cb_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('user_status'), self.user_status_cb_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('interface_state'), self.interface_state_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('send_scene'), self.send_to_clients_evt)

        QtCore.QObject.connect(self, QtCore.SIGNAL('touch_calibration_points_evt'), self.touch_calibration_points_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('touch_detected_evt'), self.touch_detected_evt)

        self.user_status = None

        self.program_vis.active_item_switched = self.active_item_switched
        self.program_vis.program_state_changed = self.program_state_changed

        self.fsm = FSM()

        # TODO do this automatically??
        # map callbacks from FSM to this instance
        self.fsm.cb_start_calibration = self.cb_start_calibration
        self.fsm.cb_waiting_for_user = self.cb_waiting_for_user
        self.fsm.cb_program_selection = self.cb_program_selection
        self.fsm.cb_waiting_for_user_calibration = self.cb_waiting_for_user_calibration
        self.fsm.cb_learning = self.cb_learning
        self.fsm.cb_running = self.cb_running
        self.fsm.is_template = self.is_template

        self.state_manager = InterfaceStateManager("PROJECTED UI", cb=self.interface_state_cb)

        cursors = rospy.get_param("~cursors", [])
        for cur in cursors:
            self.scene_items.append(PoseStampedCursorItem(self.scene, self.rpm, cur))

        self.scene_items.append(TouchTableItem(self.scene,  self.rpm, '/art/interface/touchtable/touch', self.get_scene_items_by_type(PoseStampedCursorItem)))

        self.scene_items.append(ButtonItem(self.scene, self.rpm, 0, 0, "STOP", None, self.stop_btn_clicked, 2.0, QtCore.Qt.red))
        self.scene_items[-1].setPos(self.scene.width() - self.scene_items[-1].w, self.scene.height() - self.scene_items[-1].h - 60)
        self.scene_items[-1].set_enabled(True)

        self.port = rospy.get_param("~scene_server_port", 1234)

        self.tcpServer = QtNetwork.QTcpServer(self)
        if not self.tcpServer.listen(port=self.port):

            rospy.logerr('Failed to start scene TCP server on port ' + str(self.port))

        self.tcpServer.newConnection.connect(self.newConnection)
        self.connections = []

        self.last_scene_update = None
        self.scene.changed.connect(self.scene_changed)

        self.projectors = []

        projs = rospy.get_param("~projectors", [])
        for proj in projs:
            self.add_projector(proj)

        self.art = ArtApiHelper()

    def touch_calibration_points_evt(self,  pts):

        # TODO trigger state change?
        for it in self.scene_items:

            if isinstance(it, LabelItem):
                continue

            it.set_enabled(False, True)

        self.notif(translate("UICoreRos", "Touch table calibration started. Please press the white point."), temp=False)
        self.touch_points = TouchPointsItem(self.scene, self.rpm,  pts)

    def touch_calibration_points_cb(self,  req):

        resp = TouchCalibrationPointsResponse()

        if self.fsm.state not in ['program_selection', 'learning', 'running']:
            resp.success = False
            rospy.logerr('Cannot start touchtable calibration without a user!')
            return resp

        pts = []

        for pt in req.points:

            pts.append((pt.point.x,  pt.point.y))

        self.emit(QtCore.SIGNAL('touch_calibration_points_evt'), pts)
        self.touched_sub = rospy.Subscriber('/art/interface/touchtable/touch_detected',  Empty,  self.touch_detected_cb,  queue_size=10)
        resp.success = True
        return resp

    def touch_detected_evt(self,  msg):

        if self.touch_points is None:
            return

        if not self.touch_points.next():

            self.notif(translate("UICoreRos", "Touch saved."), temp=True)

            for it in self.scene_items:

                if isinstance(it, LabelItem):
                    continue

                it.set_enabled(True, True)

            self.notif(translate("UICoreRos", "Touch table calibration finished."), temp=False)
            self.scene.removeItem(self.touch_points)
            self.touch_points = None
            self.touched_sub.unregister()

        else:

            self.notif(translate("UICoreRos", "Touch saved."), temp=True)
            self.notif(translate("UICoreRos", "Please press the next point."), temp=False)

    def touch_detected_cb(self,  msg):

        self.emit(QtCore.SIGNAL('touch_detected_evt'), msg)

    def newConnection(self):

        rospy.loginfo('Some projector node just connected.')
        self.connections.append(self.tcpServer.nextPendingConnection())
        self.connections[-1].setSocketOption(QtNetwork.QAbstractSocket.LowDelayOption, 1)
        self.emit(QtCore.SIGNAL('send_scene'), self.connections[-1])
        # TODO deal with disconnected clients!
        # self.connections[-1].disconnected.connect(clientConnection.deleteLater)

    def send_to_clients_evt(self, client=None):

        # if all connections are sending scene image, there is no need to render the new one
        if client is None:

            for con in self.connections:

                if con.bytesToWrite() == 0:
                    break

            else:
                return

        # TODO try to use Format_RGB16 - BMP is anyway converted to 32bits (send raw data instead)
        pix = QtGui.QImage(self.scene.width(), self.scene.height(), QtGui.QImage.Format_ARGB32_Premultiplied)
        painter = QtGui.QPainter(pix)
        self.scene.render(painter)
        painter.end()

        block = QtCore.QByteArray()
        out = QtCore.QDataStream(block, QtCore.QIODevice.WriteOnly)
        out.setVersion(QtCore.QDataStream.Qt_4_0)
        out.writeUInt32(0)

        img = QtCore.QByteArray()
        buffer = QtCore.QBuffer(img)
        buffer.open(QtCore.QIODevice.WriteOnly)
        pix.save(buffer, "BMP")
        out << QtCore.qCompress(img, 1)  # this seem to be much faster than using PNG compression

        out.device().seek(0)
        out.writeUInt32(block.size() - 4)

        # print block.size()

        if client is None:

            for con in self.connections:

                if con.bytesToWrite() > 0:
                    return
                con.write(block)

        else:

            client.write(block)

    def start(self):

        rospy.loginfo("Waiting for ART services...")
        self.art.wait_for_api()

        if len(self.projectors) > 0:
            rospy.loginfo("Waiting for projector nodes...")
            for proj in self.projectors:
                proj.wait_until_available()

        rospy.loginfo("Ready! Starting state machine.")

        # TODO move this to ArtApiHelper ??
        self.obj_sub = rospy.Subscriber('/art/object_detector/object_filtered', InstancesArray, self.object_cb, queue_size=1)
        self.user_status_sub = rospy.Subscriber('/art/user/status', UserStatus, self.user_status_cb, queue_size=1)

        self.touch_points = None
        self.touch_calib_srv = rospy.Service('/art/interface/projected_gui/touch_calibration', TouchCalibrationPoints, self.touch_calibration_points_cb)

        self.fsm.tr_start()

    def add_projector(self, proj_id):

        self.projectors.append(ProjectorHelper(proj_id))

    def scene_changed(self, rects):

        if len(rects) == 0:
            return
        # TODO Publish only changes? How to accumulate them (to be able to send it only at certain fps)?

        now = rospy.Time.now()
        if self.last_scene_update is None:
            self.last_scene_update = now
        else:
            if now - self.last_scene_update < rospy.Duration(1.0 / 20):
                return

        # print 1.0/(now - self.last_scene_update).to_sec()
        self.last_scene_update = now

        self.emit(QtCore.SIGNAL('send_scene'))

    def stop_btn_clicked(self):

        # TODO
        self.notif(translate("UICoreRos", "Emergency stop pressed"), temp=True)

    def interface_state_evt(self, our_state, state, flags):

        if state.system_state == InterfaceState.STATE_LEARNING:

            # TODO !!
            pass

        elif state.system_state == InterfaceState.STATE_PROGRAM_RUNNING:

            if self.program_vis.prog is None or self.program_vis.prog.id != state.program_id:

                program = self.art.load_program(state.program_id)
                if program is not None:
                    self.program_vis.set_prog(program, False)
                else:
                    pass  # TODO error

            if self.fsm.state != 'running':

                self.clear_all()
                self.program_vis.set_running()
                self.fsm.tr_running()

            # TODO updatovat program_vis itemem ze zpravy - pokud se lisi (timestamp) ??
            self.program_vis.set_active(inst_id=state.program_current_item.id)
            it = state.program_current_item

            if our_state.program_current_item.id != state.program_current_item:
                self.clear_all()

            if it.type == ProgIt.GET_READY:

                self.notif(translate("UICoreRos", "Robot is getting ready"))

            elif it.type == ProgIt.WAIT:

                if it.spec == ProgIt.WAIT_FOR_USER:
                    self.notif(translate("UICoreRos", "Waiting for user"))
                elif it.spec == ProgIt.WAIT_UNTIL_USER_FINISHES:
                    self.notif(translate("UICoreRos", "Waiting for user to finish"))

            # TODO MANIP_PICK, MANIP_PLACE
            elif it.type == ProgIt.MANIP_PICK_PLACE:

                obj_id = it.object

                if it.spec == ProgIt.MANIP_ID:

                    self.select_object(it.object)

                elif it.spec == ProgIt.MANIP_TYPE:

                    try:
                        obj_id = flags["SELECTED_OBJECT_ID"]
                    except KeyError:
                        rospy.logerr("MANIP_PICK_PLACE/MANIP_TYPE: SELECTED_OBJECT_ID flag not set")
                        pass

                    # TODO how to highlight selected object (by brain) ?
                    self.select_object_type(it.object)
                    self.add_polygon(translate("UICoreRos", "PICK POLYGON"), poly_points=self.program_vis.active_item.get_pick_polygon_points())  # TODO fixed

                self.notif(translate("UICoreRos", "Going to manipulate with object ID=") + obj_id)
                self.add_place(translate("UICoreRos", "PLACE POSE"), it.place_pose.pose.position.x, it.place_pose.pose.position.y, fixed=True)

    def interface_state_cb(self, our_state, state, flags):

        self.emit(QtCore.SIGNAL('interface_state'), our_state, state, flags)

    # callback from ProgramItem (button press)
    def program_state_changed(self, state):

        if state == 'RUNNING':

            prog = self.program_vis.get_prog()
            prog.id = 1

            if not self.art.store_program(prog):
                # TODO what to do?
                self.notif(translate("UICoreRos", "Failed to store program"), temp=True)

            else:

                self.notif(translate("UICoreRos", "Program stored. Starting..."), temp=True)

            # clear all and wait for state update from brain
            self.clear_all()
            self.fsm.tr_program_learned()

            self.art.start_program(prog.id)

        # TODO pause / stop -> fsm
        # elif state == ''

        # callback from ProgramItem
    def active_item_switched(self):

        rospy.logdebug("Program ID:" + str(self.program_vis.prog.id) + ", active item ID: " + str(self.program_vis.active_item.item.id))

        self.clear_all()
        # TODO block_id
        self.state_manager.update_program_item(self.program_vis.prog.id, self.program_vis.prog.blocks[0].id,  self.program_vis.active_item.item)

        if self.program_vis.active_item.item.type in [ProgIt.MANIP_PICK, ProgIt.MANIP_PLACE, ProgIt.MANIP_PICK_PLACE]:

            if self.program_vis.active_item.item_learned():

                self.notif(translate("UICoreRos", "This program item seems to be done"))

            else:

                # TODO vypsat jaky je to task?
                self.notif(translate("UICoreRos", "Program current manipulation task"))

            # TODO loop across program item ids - not indices!!
            idx = self.program_vis.items.index(self.program_vis.active_item)
            if idx > 0:
                for i in range(idx - 1, -1, -1):

                    it = self.program_vis.items[i]

                    if it.item.type in [ProgIt.MANIP_PLACE, ProgIt.MANIP_PICK_PLACE] and it.is_place_pose_set():

                        # TODO add "artif." object instead of place??
                        self.add_place(translate("UICoreRos", "OBJECT FROM STEP") + " " + str(it.item.id), it.item.place_pose.pose.position.x, it.item.place_pose.pose.position.y, fixed=True)
                        break

            if self.program_vis.active_item.item.spec == ProgIt.MANIP_TYPE:

                if not self.program_vis.active_item.is_object_set():

                    self.notif(translate("UICoreRos", "Select object type to be picked up"), temp=True)

                self.select_object_type(self.program_vis.active_item.item.object)

                # if program item already contains polygon - let's display it
                if self.program_vis.active_item.is_pick_polygon_set():

                    self.add_polygon(translate("UICoreRos", "PICK POLYGON"), poly_points=self.program_vis.active_item.get_pick_polygon_points(), polygon_changed=self.polygon_changed, fixed=True)

            else:

                self.notif(translate("UICoreRos", "Select object to be picked up"), temp=True)
                self.select_object(self.program_vis.active_item.item.object)

            if self.program_vis.active_item.is_object_set():

                # TODO kdy misto place pose pouzi place polygon? umoznit zmenit pose na polygon a opacne?

                if self.program_vis.active_item.is_place_pose_set():
                    (x, y) = self.program_vis.active_item.get_place_pose()
                    self.add_place(translate("UICoreRos", "PLACE POSE"), x, y, self.place_pose_changed)
                else:
                    self.notif(translate("UICoreRos", "Set where to place picked object"))
                    self.add_place(translate("UICoreRos", "PLACE POSE"), self.width / 2, self.height / 2, self.place_pose_changed)

    def place_pose_changed(self, pos):

        self.program_vis.set_place_pose(pos[0], pos[1])
        # TODO block_id
        self.state_manager.update_program_item(self.program_vis.prog.id, self.program_vis.prog.blocks[0].id,  self.program_vis.active_item.item)

    def is_template(self):

        return True

    def cb_running(self):

        pass

    def cb_learning(self):

        # TODO zobrazit instrukce k tasku
        pass

    def calib_done_cb(self, proj):

        if proj.is_calibrated():

            self.calib_proj_cnt += 1

            if self.calib_proj_cnt < len(self.projectors):

                self.projectors[self.calib_proj_cnt].calibrate(self.calib_done_cb)
            else:
                rospy.loginfo('Projectors calibrated.')
                self.fsm.tr_calibrated()

        else:

            # calibration failed - let's try again
            rospy.logerr('Calibration failed for projector: ' + proj.proj_id)
            proj.calibrate(self.calib_done_cb)

    def cb_start_calibration(self):

        if len(self.projectors) == 0:

            rospy.loginfo('No projectors to calibrate.')
            self.fsm.tr_calibrated()

        else:

            rospy.loginfo('Starting calibration of ' + str(len(self.projectors)) + ' projector(s)')

            self.calib_proj_cnt = 0

            if not self.projectors[0].calibrate(self.calib_done_cb):
                # TODO what to do?
                rospy.logerr("Failed to start projector calibration")

    def cb_waiting_for_user(self):

        self.notif(translate("UICoreRos", "Waiting for user..."))

    def cb_waiting_for_user_calibration(self):

        self.notif(translate("UICoreRos", "Please do a calibration pose"))

    def cb_program_selection(self):

        self.notif(translate("UICoreRos", "Please select a program"))

        # TODO display list of programs -> let user select -> then load it
        program = self.art.load_program(0)

        if program is not None:

            self.program_vis.set_prog(program, self.is_template())
            self.active_item_switched()
            self.fsm.tr_program_selected()
        else:
            self.notif(translate("UICoreRos", "Loading of requested program failed"), temp=True)

    def object_cb(self, msg):

        self.emit(QtCore.SIGNAL('objects'), msg)

    def object_cb_evt(self, msg):

        for obj_id in msg.lost_objects:

            self.remove_object(obj_id)
            self.notif(translate("UICoreRos", "Object") + " ID=" + str(obj_id) + " " + translate("UICoreRos", "disappeared"), temp=True)

        for inst in msg.instances:

            obj = self.get_object(inst.object_id)

            if obj:
                obj.set_pos(inst.pose.position.x, inst.pose.position.y)
            else:

                # TODO get and display bounding box
                # obj_type = self.art.get_object_type(inst.object_type)
                self.add_object(inst.object_id, inst.object_type, inst.pose.position.x, inst.pose.position.y, self.object_selected)
                self.notif(translate("UICoreRos", "New object") + " ID=" + str(inst.object_id), temp=True)

    def polygon_changed(self, pts):

        self.program_vis.set_polygon(pts)
        # TODO block_id
        self.state_manager.update_program_item(self.program_vis.prog.id, self.program_vis.prog.blocks[0].id, self.program_vis.active_item.item)

    def object_selected(self, id, selected):

        if self.fsm.state != 'learning':
            return False
        # TODO handle un-selected

        print "selected object: " + str(id)

        obj = self.get_object(id)

        # TODO test typu operace

        if self.program_vis.active_item.item.spec == ProgIt.MANIP_TYPE:

            # this type of object is already set
            if obj.object_type == self.program_vis.active_item.item.object:
                return
            else:
                # TODO remove previously inserted polygon, do not insert new place
                pass

            poly_points = []

            self.program_vis.set_object(obj.object_type)
            self.select_object_type(obj.object_type)

            for obj in self.get_scene_items_by_type(ObjectItem):
                poly_points.append(obj.get_pos())

            self.add_polygon(translate("UICoreRos", "PICK POLYGON"), poly_points, polygon_changed=self.polygon_changed)
            self.notif(translate("UICoreRos", "Check and adjust pick polygon"), temp=True)

            self.notif(translate("UICoreRos", "Set where to place picked object"), temp=True)
            self.add_place(translate("UICoreRos", "PLACE POSE"), self.width / 2, self.height / 2, self.place_pose_changed)

        elif self.program_vis.active_item.item.spec == ProgIt.MANIP_ID:

            # TODO
            pass

        # TODO block_id
        self.state_manager.update_program_item(self.program_vis.prog.id, self.program_vis.prog.blocks[0].id, self.program_vis.active_item.item)
        return True

    def user_status_cb(self, msg):

        self.emit(QtCore.SIGNAL('user_status'), msg)

    def user_status_cb_evt(self, msg):

        self.user_status = msg

        try:

            if self.user_status.user_state == UserStatus.USER_NOT_CALIBRATED:

                self.fsm.tr_user_present()

            elif self.user_status.user_state == UserStatus.USER_CALIBRATED:

                self.fsm.tr_user_calibrated()

        except MachineError:
            pass
Пример #43
0
def test():
	f = FSM('INIT')
	f.add_default_transition (Error, 'INIT')
	f.add_transition ('<', 'INIT', None, 'TAG')
	f.add_transition (ANY, 'INIT', None, 'INIT') # Ignore white space between tags

	f.add_transition ('?', 'TAG', None, 'XML_DECLARATION')
	f.add_transition (ANY, 'XML_DECLARATION', None, 'XML_DECLARATION')
	f.add_transition ('?', 'XML_DECLARATION', None, 'XML_DECLARATION_END')
	f.add_transition ('>', 'XML_DECLARATION_END', None, 'INIT')

	# Handle building tags
	f.add_transition (ANY, 'TAG', StartBuildTag, 'BUILD_TAG')
	f.add_transition (ANY, 'BUILD_TAG', BuildTag, 'BUILD_TAG')
	f.add_transition (' ', 'BUILD_TAG', None, 'ELEMENT_PARAMETERS')
	f.add_transition ('/', 'TAG', None, 'END_TAG')
	f.add_transition ('/', 'BUILD_TAG', None, 'EMPTY_ELEMENT')
	f.add_transition ('>', 'BUILD_TAG', DoneBuildTag, 'INIT')

	# Handle element parameters
	f.add_transition ('>', 'ELEMENT_PARAMETERS', DoneBuildTag, 'INIT')
	f.add_transition ('/', 'ELEMENT_PARAMETERS', None, 'EMPTY_ELEMENT')
	f.add_transition ('"', 'ELEMENT_PARAMETERS', None, 'DOUBLE_QUOTE')
	f.add_transition (ANY, 'ELEMENT_PARAMETERS', None, 'ELEMENT_PARAMETERS')

	# Handle quoting inside of parameter lists
	f.add_transition (ANY, 'DOUBLE_QUOTE', None, 'DOUBLE_QUOTE')
	f.add_transition ('"', 'DOUBLE_QUOTE', None, 'ELEMENT_PARAMETERS')

	# Handle empty element tags
	f.add_transition ('>', 'EMPTY_ELEMENT', DoneEmptyElement, 'INIT')

	# Handle end tags
	f.add_transition (ANY, 'END_TAG', StartBuildEndTag, 'BUILD_END_TAG')
	f.add_transition (ANY, 'BUILD_END_TAG', BuildEndTag, 'BUILD_END_TAG')
	f.add_transition ('>', 'BUILD_END_TAG', DoneBuildEndTag, 'INIT')

	f.process_string (XML_TEST_DATA)
	
	return len(f.stack)
Пример #44
0
    def __init__(self):

        origin = rospy.get_param("~scene_origin", [0, 0])
        size = rospy.get_param("~scene_size", [1.2, 0.75])
        rpm = rospy.get_param("~rpm", 1280)

        super(UICoreRos, self).__init__(origin[0], origin[1], size[0], size[1], rpm)

        QtCore.QObject.connect(self, QtCore.SIGNAL('objects'), self.object_cb_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('user_status'), self.user_status_cb_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('interface_state'), self.interface_state_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('send_scene'), self.send_to_clients_evt)

        QtCore.QObject.connect(self, QtCore.SIGNAL('touch_calibration_points_evt'), self.touch_calibration_points_evt)
        QtCore.QObject.connect(self, QtCore.SIGNAL('touch_detected_evt'), self.touch_detected_evt)

        self.user_status = None

        self.program_vis.active_item_switched = self.active_item_switched
        self.program_vis.program_state_changed = self.program_state_changed

        self.fsm = FSM()

        # TODO do this automatically??
        # map callbacks from FSM to this instance
        self.fsm.cb_start_calibration = self.cb_start_calibration
        self.fsm.cb_waiting_for_user = self.cb_waiting_for_user
        self.fsm.cb_program_selection = self.cb_program_selection
        self.fsm.cb_waiting_for_user_calibration = self.cb_waiting_for_user_calibration
        self.fsm.cb_learning = self.cb_learning
        self.fsm.cb_running = self.cb_running
        self.fsm.is_template = self.is_template

        self.state_manager = InterfaceStateManager("PROJECTED UI", cb=self.interface_state_cb)

        cursors = rospy.get_param("~cursors", [])
        for cur in cursors:
            self.scene_items.append(PoseStampedCursorItem(self.scene, self.rpm, cur))

        self.scene_items.append(TouchTableItem(self.scene,  self.rpm, '/art/interface/touchtable/touch', self.get_scene_items_by_type(PoseStampedCursorItem)))

        self.scene_items.append(ButtonItem(self.scene, self.rpm, 0, 0, "STOP", None, self.stop_btn_clicked, 2.0, QtCore.Qt.red))
        self.scene_items[-1].setPos(self.scene.width() - self.scene_items[-1].w, self.scene.height() - self.scene_items[-1].h - 60)
        self.scene_items[-1].set_enabled(True)

        self.port = rospy.get_param("~scene_server_port", 1234)

        self.tcpServer = QtNetwork.QTcpServer(self)
        if not self.tcpServer.listen(port=self.port):

            rospy.logerr('Failed to start scene TCP server on port ' + str(self.port))

        self.tcpServer.newConnection.connect(self.newConnection)
        self.connections = []

        self.last_scene_update = None
        self.scene.changed.connect(self.scene_changed)

        self.projectors = []

        projs = rospy.get_param("~projectors", [])
        for proj in projs:
            self.add_projector(proj)

        self.art = ArtApiHelper()
Пример #45
0
class RobotCat(Char):
    def __init__(self):
        self.FSM = FSM(self)

        # States
        self.FSM.addState("Sleep", Sleep(self.FSM))
        self.FSM.addState("Walk", Walk(self.FSM))
        self.FSM.addState("Meow", Meow(self.FSM))

        # Transitions
        self.FSM.addTransition("toSleep", ToSleep("Sleep"))
        self.FSM.addTransition("toWalk", ToWalk("Walk"))
        self.FSM.addTransition("toMeow", ToMeow("Meow"))

        self.FSM.setState("Sleep")

    def execute(self):
        self.FSM.execute()
Пример #46
0
    helices[-1].append(fsm.input_symbol)

def finishThreeTen(fsm):
    print("finishThreeTen")
    print("310 :", helices[-1])

def finishAlpha(fsm):
    print("finishAlpha")
    print("Alpha :", helices[-1])

def anyTransition(fsm):
    print("anyTransition")

helices = []
non_helix_symbols = " BTSE"
f = FSM('NON_HELIX', helices)
f.set_default_transition(Error, 'NON_HELIX')
f.add_transition_any('NON_HELIX', anyTransition, 'NON_HELIX')
f.add_transition('H', 'NON_HELIX', startHelix, 'ALPHA_HELIX')
f.add_transition('H', 'ALPHA_HELIX', continueHelix, 'ALPHA_HELIX')
f.add_transition('G', 'ALPHA_HELIX', continueHelix, 'ALPHA_HELIX')
f.add_transition('G', 'NON_HELIX', startHelix, '310_HELIX')
f.add_transition('G', '310_HELIX', continueHelix, '310_HELIX')
f.add_transition('H', '310_HELIX', continueHelix, 'ALPHA_HELIX')
f.add_transition_list(non_helix_symbols, '310_HELIX', finishThreeTen, 'NON_HELIX')
f.add_transition_list(non_helix_symbols, 'ALPHA_HELIX', finishAlpha, 'NON_HELIX')

seq = " HHHGG TTHHHHH GGHH GGGG "
for s in seq:
    f.process(s)
    print(s, f.current_state)
Пример #47
0
	global coach
	coach = Coach()

	global predictor
#	predictor = Predictor()

	initedOnce = True




fsm = FSM([(TacticType.START,   TacticType.OFFENCE, lambda x: Coach().isAttack(x)),
	       (TacticType.START,   TacticType.DEFENCE, lambda x: not Coach().isAttack(x)),
	       (TacticType.OFFENCE, TacticType.DEFENCE, lambda x: not Coach().isAttack(x)),
	       (TacticType.DEFENCE, TacticType.OFFENCE, lambda x: Coach().isAttack(x)),
	       (TacticType.DEFENCE, TacticType.DEFENCE, lambda x: not Coach().isAttack(x)),
	       (TacticType.OFFENCE, TacticType.OFFENCE, lambda x: Coach().isAttack(x)),
	       ])

fsm.start(TacticType.START)

#----------------------------------------------------------

class MyStrategy:
	def moveToPoint(self,me,x,y,move):
		dist = me.get_distance_to(x,y)

		angle = me.get_angle_to(x,y)
		k = 1
		if (angle < pi/2 and angle > -pi/2) or dist > 150:
Пример #48
0
#!/bin/python
# coding: utf-8

from fsm import State, Transition, FSM

import time, threading  
def wait_input(fsm):  
    cmds = {"i":"Idle", "w":"Walk", "r":"Run", "a":"Attach"};
    while fsm.is_active():
        c = raw_input("[iwra]: ")
        if c in cmds.keys():
            fsm.set_state(cmds[c])
    
if __name__ == "__main__":
    s_idle = State("Idle")
    s_walk = State("Walk")
    s_run = State("Run")
    s_attack = State("Attack")
    
    fsm = FSM()
    fsm.start(s_idle)

    threading.Thread(target = wait_input, args=(fsm,)).start()  
    
    for i in xrange(10):
        fsm.update()
        time.sleep(1)

    fsm.stop()
Пример #49
0
        print("Detectando cubo")
        time.sleep(random.random()*3)

    def next_state(self):
        return 3

class AvanzarACubo(State):

    def __init__(self, _id):
        State.__init__(self,_id)

    def run_state(self):
        print("Avanzando a cubo")
        time.sleep(random.random()*3)

    def next_state(self):
        return FSM.END

if __name__ == "__main__":

    bC = BuscarCubo(1)
    dC = DetectartCubo(2)
    aaC = AvanzarACubo(3)

    machine = FSM([bC, dC, aaC, 3], 1)

    while not machine.isEND():
        machine.run()

    print ("This is the END of it")
Пример #50
0
	def __init__(self, *args, **kwargs):
		FSM.__init__(self, *args, **kwargs)
Пример #51
0
                key = line.lower().split()[0]
                if key not in keys:
                    raise ValueError('Keyword {0} not receognized'.format(key))
                input_dict[key] = line.split()[1]

    return input_dict

###############################################################################

if __name__ == '__main__':

    # Set up parser for reading the input filename from the command line
    parser = argparse.ArgumentParser(description='A freezing string method transition state search')
    parser.add_argument('file', type=str, metavar='FILE', help='An input file describing the FSM job to execute')
    args = parser.parse_args()

    # Set output directory
    input_file = args.file
    output_dir = os.path.abspath(os.path.dirname(input_file))

    # Initialize the logging system
    log_level = logging.INFO
    initializeLog(log_level, os.path.join(output_dir, 'FSM.log'))

    # Read input file
    fsm_arguments = readInput(input_file)

    fsm = FSM(**fsm_arguments)

    fsm.execute()
Пример #52
0
	def _init(self):
		f = FSM(0)
		f.arg = ""
		f.add_default_transition(self._error, 0)
		# normally add text to args
		f.add_transition(ANY, 0, self._addtext, 0)
		f.add_transition_list(" \t", 0, self._wordbreak, 0)
		f.add_transition_list(";\n", 0, self._doit, 0)
		# slashes
		f.add_transition("\\", 0, None, 1)
		f.add_transition("\\", 3, None, 6)
		f.add_transition(ANY, 1, self._slashescape, 0)
		f.add_transition(ANY, 6, self._slashescape, 3)
		# vars 
		f.add_transition("$", 0, self._startvar, 7)
		f.add_transition("{", 7, self._vartext, 9)
		f.add_transition_list(self.VARNAME, 7, self._vartext, 7)
		f.add_transition(ANY, 7, self._endvar, 0)
		f.add_transition("}", 9, self._endvar, 0)
		f.add_transition(ANY, 9, self._vartext, 9)
		# vars in singlequote
		f.add_transition("$", 3, self._startvar, 8)
		f.add_transition("{", 8, self._vartext, 10)
		f.add_transition_list(self.VARNAME, 8, self._vartext, 8)
		f.add_transition(ANY, 8, self._endvar, 3)
		f.add_transition("}", 10, self._endvar, 3)
		f.add_transition(ANY, 10, self._vartext, 10)
		# single quotes quote all
		f.add_transition("'", 0, None, 2)
		f.add_transition("'", 2, self._singlequote, 0)
		f.add_transition(ANY, 2, self._addtext, 2)
		# double quotes allow embedding word breaks and such
		f.add_transition('"', 0, None, 3)
		f.add_transition('"', 3, self._doublequote, 0)
		f.add_transition(ANY, 3, self._addtext, 3)
		# single-quotes withing double quotes
		f.add_transition("'", 3, None, 5)
		f.add_transition("'", 5, self._singlequote, 3)
		f.add_transition(ANY, 5, self._addtext, 5)
		self._fsm = f