def test_execute_transition_not_found(self):
     fsm = FSM("off")
     fsm.add_transition("play", "off", "music", "on")
     self.assertRaises(Exception, fsm.execute, "stop")
     self.assertIsNone(fsm.action)
     self.assertIsNone(fsm.prev_state)
     self.assertEqual("off", fsm.current_state)
Beispiel #2
0
 def __init__(self):
     self.keypad = Keypad()
     self.fsm = FSM(self)
     self.ledboard = LedBoard()
     self.override_signal = None
     self.bulbNumber = ""  #which bulb to be lit, LID
     self.ledTime = ""  #duration of lit LED, Ldur
    def __init__(self, initial_state):
        self.FSM = FSM(initial_state)

        self.FSM.add_transition("Antelope", "Hungry", "Eat", "Fed")
        self.FSM.add_transition("Antelope", "Fed", "Sleep", "Hungry")
        self.FSM.add_transition("Hunter", "Hungry", "Run away")
        self.FSM.add_transition("Hunter", "Fed", "Run away", "Hungry")
        self.FSM.add_transition("Tree", "Hungry", "Sleep")
        self.FSM.add_transition("Tree", "Fed", "Look", "Hungry")
Beispiel #4
0
def main():
    print("Test program")

    task_1_config = {
        "fnc": read_uart,
        "args": (),
        "periodic": True,
        "period": 0.1,
        "trace_dependent": False,
        "entry_states": ("init", "griffin_turning_on", "griffin_started"),
        "end_state": "no_change"
    }
    task_2_config = {
        "fnc": griffin_on,
        "args": (),
        "periodic": False,
        "execution_time": 2,
        "trace_dependent": False,
        "entry_states": ("init"),
        "end_state": "griffin_turning_on"
    }
    task_3_config = {
        "fnc": check_for_starting,
        "args": (),
        "periodic": True,
        "period": 0.5,
        "trace_dependent": True,
        "entry_states": ("griffin_turning_on"),
        "end_state": "return_value"
    }
    task_4_config = {
        "fnc": change_state,
        "args": (),
        "periodic": False,
        "execution_time": 10,
        "entry_states": ("init", "second_state"),
        "end_state": "return_value"
    }
    task_when_second_state_config = {
        "fnc": foo,
        "args": ("Now in second_state", ),
        "periodic": False,
        "execution_time": 0,
        "entry_states": ("second_state"),
        "end_state": "second_state"
    }
    tasks = {
        "task_1": task_1_config,
        "task_2": task_2_config,
        "task_3": task_3_config
    }

    trace = ""
    fsm = FSM(tasks, trace)

    while True:
        fsm.run()
    def __init__(self, inputComponents, velocityComponents):
        Observer.__init__(self)
        Publisher.__init__(self)
        self.inputComponents = inputComponents
        self.velocityComponents = velocityComponents
        self.inputMapper = InputMapper()

        self.fsm = FSM()
        FSMGraphFactory(self.fsm, GraphIDs.Moving)
    def term(self):
        if self.token() not in {"|",")",None}:
            fsm = self.factor()
        else:
            fsm = FSM("")
 
        while self.token() not in {"|",")",None}:
            fsm.concatenate(self.factor())
    
        return fsm
Beispiel #7
0
    def term(self):
        if self.token() not in {"|", ")", None}:
            fsm = self.factor()
        else:
            fsm = FSM("")

        while self.token() not in {"|", ")", None}:
            fsm.concatenate(self.factor())

        return fsm
Beispiel #8
0
	def __init__(self):
		
		self._refbox_state_to_str = lambda state: refbox_state_to_str[state]
		self._refbox_states_to_str = lambda list_of_states: map(self._refbox_state_to_str , list_of_states)
		
		self._bmbox_state_to_str = lambda state: bmbox_state_to_str[state]
		self._bmbox_states_to_str = lambda list_of_states: map(self._bmbox_state_to_str , list_of_states)
		
		self.__current_goal = None
		self.__current_manual_operation = None
		self.__current_referee_score = None
		
		self.__fsm = FSM(
			bmbox_state_to_str,
			(
				(BmBoxState.WAITING_CLIENT, BmBoxState.END), # allowed transitions from BmBoxState.START
				(BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.WAITING_CLIENT
				(BmBoxState.WAITING_MANUAL_OPERATION, BmBoxState.TRANSMITTING_GOAL, BmBoxState.TRANSMITTING_SCORE, BmBoxState.END), # allowed transitions from BmBoxState.READY
				(BmBoxState.COMPLETED_MANUAL_OPERATION, BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.WAITING_MANUAL_OPERATION
				(BmBoxState.TRANSMITTING_GOAL, BmBoxState.WAITING_MANUAL_OPERATION, BmBoxState.END), # allowed transitions from BmBoxState.COMPLETED_MANUAL_OPERATION
				(BmBoxState.EXECUTING_GOAL, BmBoxState.END), # allowed transitions from BmBoxState.TRANSMITTING_GOAL
				(BmBoxState.WAITING_RESULT, BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.EXECUTING_GOAL
				(BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.WAITING_RESULT
				(BmBoxState.END, ), # allowed transitions from BmBoxState.TRANSMITTING_SCORE
				(BmBoxState.END, ), # allowed transitions from BmBoxState.END
			),
			BmBoxState.START
		)
		
		self.__exception_states = [RefBoxState.STOP, RefBoxState.ERROR, RefBoxState.GLOBAL_TIMEOUT]
		
		self.__refbox_state = RefBoxState()
		self.__status = SystemStatus()
		self.__status.status = SystemStatus.NORMAL
		
		self.__state_pub = rospy.Publisher("bmbox/bmbox_state", BmBoxState, queue_size=10)
		self.__status_pub = rospy.Publisher("rsbb_system_status/bmbox", SystemStatus, queue_size=10)
		
		self.__refbox_state_observer = StateObserver(self.__exception_states, self.__refbox_state, refbox_state_to_str)

		self.__pub_thread = Thread(name="pub_thread", target=self.__pub_thread)
		self.__pub_thread.start()
		
		self._start_benchmark_server = rospy.Service("bmbox/start_benchmark", StartBenchmark, self.__start_benchmark_callback)
		self._manual_operation_complete_server = rospy.Service("bmbox/manual_operation_complete", ManualOperationComplete, self.__manual_operation_complete_callback)
		self._goal_started_server = rospy.Service("bmbox/goal_execution_started", GoalStarted, self.__goal_started_callback)
		self._goal_complete_server = rospy.Service("bmbox/goal_complete", GoalComplete, self.__goal_complete_callback)
		self._goal_complete_server = rospy.Service("bmbox/referee_score", RefereeScore, self.__referee_score_callback)
		self._stop_benchmark_server = rospy.Service("bmbox/stop_benchmark", StopBenchmark, self.__stop_benchmark_callback)
		
		
		
		
		### TEST
		self.tmp = 0
class InputSystem(Observer, Publisher):
    """
        This system takes raw inpout from the keyboard and translates into actions 
        and states held in an instance of "InputMapper".

        All code to do so is held within the InputMapper.
    """
    def __init__(self, inputComponents, velocityComponents):
        Observer.__init__(self)
        Publisher.__init__(self)
        self.inputComponents = inputComponents
        self.velocityComponents = velocityComponents
        self.inputMapper = InputMapper()

        self.fsm = FSM()
        FSMGraphFactory(self.fsm, GraphIDs.Moving)

    def handleInput(self):
        mappedInput = self.inputMapper.MapInput()
        for ID in self.inputComponents:
            if self.fsm.run(mappedInput,
                            inputComponent=self.inputComponents[ID],
                            velocityComponent=self.velocityComponents[ID]):
                inputEvent = Event()
                inputEvent.entityID = ID
                self.fsm.transitionFunctions.process(inputEvent)
                self.publishEvent(inputEvent)
def p_atom( p ) :
    '''atom : LPAREN expr RPAREN
            | SYMBOL'''

    if len(p) == 4:
        p[0] = p[2]
    else:
        p[0] = FSM(p[1])
def p_term( p ) :
    '''term : factor term
            | '''
    if len(p) == 3:
        p[1].concatenate(p[2])
        p[0] = p[1]
    else:
        p[0] = FSM("")
Beispiel #12
0
def start(bot, update):
    # inserts new user to database (if not exist) and sets initial state to 'initial'
    state = database_manager.get_user_state(update.message.chat.id)
    if state != 'initial':
        database_manager.set_user_state(update.message.chat.id, 'initial')
    fsm = FSM('initial')
    fsm.machine.start(update)
    database_manager.set_user_state(update.message.chat.id, fsm.machine.state)
Beispiel #13
0
def main():
    parser = argparse.ArgumentParser("Homework 1 dialog manager system")
    parser.add_argument("-v", "--verbose", action="count", default=0)
    parser.add_argument("-s", "--system", choices=["FSM"])
    parser.add_argument("-l", "--NLU", default="Default")
    parser.add_argument("-g", "--NLG", default="Default")
    args = parser.parse_args()

    system = args.system
    NLU = args.NLU
    NLG = args.NLG

    print("NLU = {}, system = {}, NLG = {}".format(NLU, system, NLG))

    NLUModule = None
    DMModule = None
    NLGModule = None

    if NLU == "Default":
        NLUModule = NLUDefault()

    if NLG == "Default":
        NLGModule = NLGDefault()

    if system == "FSM":
        DMModule = FSM(NLUModule, NLGModule)
    else:
        print("{} not implemented".format(system))
        return

    print("Welcome to the HW2 Dialog System")
    while True:
        inputStr = input("> ")
        if inputStr == "Quit":
            break

        try:
            outputStr = DMModule.execute(inputStr)
        except Exception as e:
            print(e)
            break

        print(outputStr)
Beispiel #14
0
def index(comm):
    global command
    items = comm.split(',')
    orientation = items[0]
    speed = int(items[1])
    command = FSM(orientation, speed)
    print command
    return template('<b>command: {{comm}} length queue: {{length}}</b>',
                    comm=comm,
                    length=len(comm))
Beispiel #15
0
    def __init__(self, options, args):
        self.TestSuite = False  # used by pmt nruns logic
        self.module = dict()  # dict of modules keyed by name
        self.mp = dict()  # dict of model programs keyed by same module name

        # Populate self.module and self.mp from modules named in command line args
        # Models that users write are just modules, not classes (types)
        #  so we find out what type to wrap each one in
        #  by checking for one of each type's required attributes using hasattr
        for mname in args:  # args is list of module name
            self.module[mname] = __import__(mname)
            if hasattr(self.module[mname], 'graph'):
                self.mp[mname] = FSM(self.module[mname], options.exclude,
                                     options.action)
            # for backwards compatibility we accept all of these test_suite variants
            elif (hasattr(self.module[mname], 'testSuite')
                  or hasattr(self.module[mname], 'testsuite')
                  or hasattr(self.module[mname], 'test_suite')):
                self.mp[mname] = TestSuite(self.module[mname], options.exclude,
                                           options.action)
                self.TestSuite = True  # used by pmt nruns logic
            elif self.module[mname].__doc__.strip().upper().startswith(
                    'PYMODEL CONFIG'):
                pass  # configuration module, merely importing it did all the work
            else:
                # got this far, should be a ModelProgram -- if not, crash
                self.mp[mname] = ModelProgram(self.module[mname],
                                              options.exclude, options.action)

        # Now that all modules have been imported and executed their __init__
        #  do a postprocessing pass over all model objects
        #  to process metadata that might be affected by configuration modules
        for mp in self.mp.values():
            mp.post_init()

        # set of all anames in all model programs - the vocabulary of the product
        self.anames = set().union(
            *
            [set([a.__name__ for a in mp.actions]) for mp in self.mp.values()])
        # print 'anames %s' % self.anames # DEBUG

        # set of anames of all observable actions in all model programs
        # observables obtain arg values from the environment, not parameter gen.
        self.observables = set().union(*[
            set([a.__name__ for a in mp.module.observables])
            for mp in self.mp.values()
        ])
        # FSM and TestSuite must have .observables
        # print 'observables %s' % self.observables # DEBUG

        # dict from aname to set of all m where aname is in vocabulary
        self.vocabularies = \
            dict([(aname, set([m for m in self.mp if aname in
                               [a.__name__ for a in self.mp[m].actions]]))
                  for aname in self.anames])
 def test_execute_transition_found(self):
     fsm = FSM("off")
     fsm.add_transition("play", "off", "music", "on")
     fsm.execute("play")
     self.assertEqual("music", fsm.action)
     self.assertEqual("off", fsm.prev_state)
     self.assertEqual("on", fsm.current_state)
Beispiel #17
0
 def __init__(self, initerestring, events):
     #initial spec ERE to start from
     self.erestring = initerestring
     #all events relating to ERE
     self.events = events
     #dictionary of quick lookup terms
     self.t = r"\(|\)|\~|\&|\||\*|\+|epsilon|\^|empty|\w+"
     self.initERE = self.genERE()
     self.symbolist = [Symbol.stringToRef[i] for i in self.events]
     self.fsm = FSM.getFSM(self.initERE, self.symbolist)
     self.currstate = self.initERE
     self.violated = False
     self.reported = False
     self.state_string = "s0"
Beispiel #18
0
def fsm_from_expression(exp):

    fsm_stack = []
    for char in exp:
        if char in SIGMA or char == '1':
            fsm = FSM()
            fsm_stack.append(fsm.create(char))
        elif char == '.':
            second_fsm = fsm_stack.pop()
            first_fsm = fsm_stack.pop()
            fsm_stack.append(concat(first_fsm, second_fsm))

        elif char == '+':
            first_fsm = fsm_stack.pop()
            second_fsm = fsm_stack.pop()
            fsm_stack.append(add(first_fsm, second_fsm))

        elif char == '*':
            fsm = fsm_stack.pop()
            fsm_stack.append(iteration(fsm))

    if len(fsm_stack) != 1:
        raise IndexError
    return fsm_stack[0]
Beispiel #19
0
    def atom(self):
        if self.token() == "(":
            self.next()
            fsm = self.expr()
            if self.token() == ")":
                self.next()
            else:
                raise ValueError

        elif self.token() not in {")", "|", "*"}:
            fsm = FSM(self.token())
            self.next()
        else:
            raise ValueError

        return fsm
Beispiel #20
0
def main():

    trans = MyTransitions()
    fsm = {}
    for n in range(0, 4):
        fsm[n] = FSM([
            ("Sova", "Äta", 'hungrig', lambda x: x == trans.sova('hungrig')),
            ("Sova", "Umgås", 'glad', lambda x: x == trans.sova('glad')),
            ("Sova", "Jobba", 'tjäna', lambda x: x == trans.sova('tjäna')),
            ("Sova", "Dricka", 'törstig',
             lambda x: x == trans.sova('törstig')),
            ("Äta", "Sova", 'trött', lambda x: x == trans.ata('trött')),
            ("Äta", "Jobba", 'tjäna', lambda x: x == trans.ata('tjäna')),
            ("Äta", "Umgås", 'glad', lambda x: x == trans.ata('glad')),
            ("Umgås", "Äta", 'hungrig', lambda x: x == trans.umgas('hungrig')),
            ("Umgås", "Dricka", 'törstig',
             lambda x: x == trans.umgas('törstig')),
            ("Umgås", "Sova", 'trött', lambda x: x == trans.umgas('trött')),
            ("Jobba", "Sova", 'trött', lambda x: x == trans.jobba('trött')),
            ("Jobba", "Äta", 'hungrig', lambda x: x == trans.jobba('hungrig')),
            ("Jobba", "Dricka", 'törstig',
             lambda x: x == trans.jobba('törstig')),
            ("Jobba", "Jobba", 'tjäna', lambda x: x == trans.jobba('tjäna')),
            ("Jobba", "Handla", 'köpa', lambda x: x == trans.jobba('köpa')),
            ("Handla", "Äta", 'hungrig',
             lambda x: x == trans.handla('hungrig')),
            ("Handla", "Umgås", 'glad', lambda x: x == trans.handla('glad')),
            ("Handla", "Jobba", 'tjäna', lambda x: x == trans.handla('tjäna')),
            ("Dricka", "Sova", 'trött', lambda x: x == trans.dricka('trött')),
            ("Dricka", "Jobba", 'tjäna', lambda x: x == trans.dricka('tjäna')),
            ("Dricka", "Umgås", 'glad', lambda x: x == trans.dricka('glad')),
            ("Dricka", "Handla", 'köpa', lambda x: x == trans.dricka('köpa')),
            ("Dricka", "Äta", 'hungrig',
             lambda x: x == trans.dricka('hungrig'))
        ])

        name = 'actor' + str(n)
        actors[name] = Actor(fsm[n], name, dispatcher)

    dispatcher.addClients(actors)
    printCommands()
    cmd = input()
    while (not cmd == 'quit'):
        doCommand(cmd)
        cmd = input()
Beispiel #21
0
def create(**actions):
    S_init = STATE('init')
    S_error = STATE('error')
    S_state = STATE('state', enter=actions['state'])
    S_event = STATE('event', enter=actions['event'])
    S_init.set_events([
        EVENT('state', [], S_state),
    ])
    S_error.set_events([])
    S_state.set_events([
        EVENT('state', [], S_state),
        EVENT('enter', [actions['enter']]),
        EVENT('exit', [actions['exit']]),
        EVENT('event', [], S_event),
        EVENT('error', [], S_error),
    ])
    S_event.set_events([
        EVENT('action', [actions['action']]),
        EVENT('state', [], S_state),
        EVENT('event', [], S_event),
        EVENT('error', [], S_error),
    ])
    return FSM([S_init, S_error, S_state, S_event])
Beispiel #22
0
class RefBoxComm:
	
	def __init__(self):
		
		self._refbox_state_to_str = lambda state: refbox_state_to_str[state]
		self._refbox_states_to_str = lambda list_of_states: map(self._refbox_state_to_str , list_of_states)
		
		self._bmbox_state_to_str = lambda state: bmbox_state_to_str[state]
		self._bmbox_states_to_str = lambda list_of_states: map(self._bmbox_state_to_str , list_of_states)
		
		self.__current_goal = None
		self.__current_manual_operation = None
		self.__current_referee_score = None
		
		self.__fsm = FSM(
			bmbox_state_to_str,
			(
				(BmBoxState.WAITING_CLIENT, BmBoxState.END), # allowed transitions from BmBoxState.START
				(BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.WAITING_CLIENT
				(BmBoxState.WAITING_MANUAL_OPERATION, BmBoxState.TRANSMITTING_GOAL, BmBoxState.TRANSMITTING_SCORE, BmBoxState.END), # allowed transitions from BmBoxState.READY
				(BmBoxState.COMPLETED_MANUAL_OPERATION, BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.WAITING_MANUAL_OPERATION
				(BmBoxState.TRANSMITTING_GOAL, BmBoxState.WAITING_MANUAL_OPERATION, BmBoxState.END), # allowed transitions from BmBoxState.COMPLETED_MANUAL_OPERATION
				(BmBoxState.EXECUTING_GOAL, BmBoxState.END), # allowed transitions from BmBoxState.TRANSMITTING_GOAL
				(BmBoxState.WAITING_RESULT, BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.EXECUTING_GOAL
				(BmBoxState.READY, BmBoxState.END), # allowed transitions from BmBoxState.WAITING_RESULT
				(BmBoxState.END, ), # allowed transitions from BmBoxState.TRANSMITTING_SCORE
				(BmBoxState.END, ), # allowed transitions from BmBoxState.END
			),
			BmBoxState.START
		)
		
		self.__exception_states = [RefBoxState.STOP, RefBoxState.ERROR, RefBoxState.GLOBAL_TIMEOUT]
		
		self.__refbox_state = RefBoxState()
		self.__status = SystemStatus()
		self.__status.status = SystemStatus.NORMAL
		
		self.__state_pub = rospy.Publisher("bmbox/bmbox_state", BmBoxState, queue_size=10)
		self.__status_pub = rospy.Publisher("rsbb_system_status/bmbox", SystemStatus, queue_size=10)
		
		self.__refbox_state_observer = StateObserver(self.__exception_states, self.__refbox_state, refbox_state_to_str)

		self.__pub_thread = Thread(name="pub_thread", target=self.__pub_thread)
		self.__pub_thread.start()
		
		self._start_benchmark_server = rospy.Service("bmbox/start_benchmark", StartBenchmark, self.__start_benchmark_callback)
		self._manual_operation_complete_server = rospy.Service("bmbox/manual_operation_complete", ManualOperationComplete, self.__manual_operation_complete_callback)
		self._goal_started_server = rospy.Service("bmbox/goal_execution_started", GoalStarted, self.__goal_started_callback)
		self._goal_complete_server = rospy.Service("bmbox/goal_complete", GoalComplete, self.__goal_complete_callback)
		self._goal_complete_server = rospy.Service("bmbox/referee_score", RefereeScore, self.__referee_score_callback)
		self._stop_benchmark_server = rospy.Service("bmbox/stop_benchmark", StopBenchmark, self.__stop_benchmark_callback)
		
		
		
		
		### TEST
		self.tmp = 0
	
	
	def __pub_thread(self):
		r = rospy.Rate(STATE_UPDATE_RATE)
		while not rospy.is_shutdown():
			self.__state_pub.publish(self.__fsm.state(), self.__fsm.payload())
			self.__publish_system_status("executing")
			r.sleep()
		self.__state_pub.unregister()
	
	def __publish_system_status(self, d = ""):
		self.__status.header.stamp = rospy.Time.now()
		self.__status.status_description = d
		self.__status_pub.publish(self.__status)
	
	def __update_refbox_state(self, refbox_state):
		self.__refbox_state = refbox_state
		self.__refbox_state_observer.update(refbox_state)
		
		print "\n\nbenchmark_state:        %s\ngoal_execution_state:   %s\nmanual_operation_state: %s\n" % (self._refbox_state_to_str(self.__refbox_state.benchmark_state),\
		self._refbox_state_to_str(self.__refbox_state.goal_execution_state),\
		self._refbox_state_to_str(self.__refbox_state.manual_operation_state))
		
	
	
	def __start_benchmark_callback(self, request):
		rospy.loginfo("start_benchmark_callback")
		
		if not self.is_benchmark_running():
			rospy.loginfo("start_benchmark_callback: benchmark not running")
		
		if not self.check_preconditions(bmbox_states=[BmBoxState.WAITING_CLIENT, BmBoxState.END], log_function = rospy.logerr):
			rospy.logwarn("start_benchmark_callback: inconsistent states or benchmark not running")
		
		self.__update_refbox_state(request.refbox_state)
		
		return StartBenchmarkResponse(True)
	
	def __goal_started_callback(self, request):
		rospy.loginfo("goal_started_callback")
		
		### TEST
#		if self.tmp < 5:
#			self.tmp += 1
#			print "TEST __goal_started_callback: return GoalStartedResponse(False)"
#			return GoalStartedResponse(False)

		if not self.is_benchmark_running():
			rospy.loginfo("goal_started_callback: benchmark not running")
		
		if self.__current_goal == None:
			rospy.logerr("goal_started_callback: cannot accept goal execution started event. No goal execution is pending")
			self.__update_refbox_state(request.refbox_state)
			return GoalStartedResponse(False)
		
		if not self.check_preconditions(bmbox_states=[BmBoxState.TRANSMITTING_GOAL, BmBoxState.END], log_function = rospy.logerr):
			rospy.logwarn("goal_started_callback: inconsistent states or benchmark not running")
		
		self.__update_refbox_state(request.refbox_state)
		
		return GoalStartedResponse(True)
	
	def __goal_complete_callback(self, request):
		rospy.loginfo("goal_complete_callback")
		
		### TEST
#		if self.tmp < 5 and request.refbox_state.benchmark_state == RefBoxState.GLOBAL_TIMEOUT:
#			self.tmp += 1
#			print "TEST __goal_complete_callback (GLOBAL_TIMEOUT): return GoalCompleteResponse(False)"
#			return GoalCompleteResponse(False)
		
		if not self.is_benchmark_running():
			rospy.loginfo("goal_complete_callback: benchmark not running")
		
		if self.__current_goal == None:
			rospy.logerr("goal_complete_callback: cannot accept goal complete event. No goal execution is pending")
			self.__update_refbox_state(request.refbox_state)
			return GoalCompleteResponse(False)
		else:
			if request.goal_timeout:
				self.__current_goal.set_has_timed_out()
			else:
				self.__current_goal.set_result_string(request.goal_result)
		
		if not self.check_preconditions(bmbox_states=[BmBoxState.TRANSMITTING_GOAL, BmBoxState.EXECUTING_GOAL, BmBoxState.WAITING_RESULT, BmBoxState.END], log_function = rospy.logerr):
			rospy.logwarn("goal_complete_callback: inconsistent states or benchmark not running")
		
		self.__update_refbox_state(request.refbox_state)
		
		return GoalCompleteResponse(True)
	
	def __referee_score_callback(self, request):
		rospy.loginfo("referee_score_callback")
		
		try:
			self.__current_referee_score = yaml.load(request.score)
			self.save_and_publish_score()
		except yaml.YAMLError as e:
			rospy.logerr("referee_score_callback: YAMLError while parsing refere score yaml string\n%s"%e)
		
		return RefereeScoreResponse(True)
	
	def __manual_operation_complete_callback(self, request):
		rospy.loginfo("manual_operation_complete_callback")
		
		### TEST
#		if self.tmp > 5:
#			self.tmp += 1
#			print "TEST __manual_operation_complete_callback: return ManualOperationCompleteResponse(False)"
#			return ManualOperationCompleteResponse(False)
		
		if not self.is_benchmark_running():
			rospy.loginfo("manual_operation_complete_callback: benchmark not running")
		
		if self.__current_manual_operation == None:
			rospy.logerr("manual_operation_complete_callback: cannot accept manual operation result. No manual operation is pending")
			self.__update_refbox_state(request.refbox_state)
			return ManualOperationCompleteResponse(False)
		else:
			self.__current_manual_operation.set_result(request.manual_operation_result)
		
		if not self.check_preconditions(bmbox_states=[BmBoxState.WAITING_MANUAL_OPERATION, BmBoxState.END], log_function = rospy.logerr):
			rospy.logwarn("manual_operation_complete_callback: inconsistent states or benchmark not running")
		
		self.__update_refbox_state(request.refbox_state)
		
		return ManualOperationCompleteResponse(True)
	
	def __stop_benchmark_callback(self, request):
		rospy.loginfo("stop_benchmark_callback")
		
		self.__update_refbox_state(request.refbox_state)
		
		return StopBenchmarkResponse(True)
	
	
	
	
	def _wait_refbox_connection(self):
		rospy.logdebug("RefBoxComm._wait_refbox_connection()")
		
		if not self.is_benchmark_running():
			rospy.loginfo("wait_refbox_connection: benchmark not running")
		
		if not self.check_preconditions(bmbox_states=[BmBoxState.START, BmBoxState.END], log_function = rospy.logerr):
			rospy.logerr("_wait_refbox_connection: can not execute request")
			return
		
		self.__fsm.update(BmBoxState.WAITING_CLIENT)
		
		# woken by start_benchmark_callback
		self.__refbox_state_observer.wait_benchmark_state_transition(from_state = RefBoxState.START, to_states = [RefBoxState.EXECUTING_BENCHMARK])
		
		### normal post conditions:
		self.__fsm.update(BmBoxState.READY)
		self.__current_manual_operation = None
		return
	
	def request_manual_operation(self, manual_operation_object=None):
		"""
		Requests a manual operation to the refbox.
		A manual operation consists of a request to the refbox operator to do something.
		It is possible to prompt the refbox operator to write a response, that will be returned as a string.
		This function is blocking, meaning the function will only return after the manual operation is complete.
		:param ManualOperationObject manual_operation_object: The manual operation object, containing the request and the result of the of the manual operation. The result is set after the manual operation has been completed by the refbox operator.
		"""
		
		rospy.logdebug("RefBoxComm.request_manual_operation()")
		
		if not isinstance(manual_operation_object, ManualOperationObject):
			rospy.logerr("request_manual_operation: not isinstance(manual_operation_object, ManualOperationObject)")
			return
		
		if not self.is_benchmark_running():
			rospy.loginfo("request_manual_operation: benchmark not running")
			return
		
		if self.__current_manual_operation != None:
			rospy.logerr("request_manual_operation: another manual operation request is pending")
			return
		
		if not self.check_preconditions(bmbox_states=[BmBoxState.READY, BmBoxState.END], manual_operation_states=[RefBoxState.READY]):
			rospy.loginfo("request_manual_operation: can not execute request")
			return
		
		
		self.__current_manual_operation = manual_operation_object
		
		self.__fsm.update(BmBoxState.WAITING_MANUAL_OPERATION, self.__current_manual_operation.get_request())
		
		try:
			
			execute_manual_operation = rospy.ServiceProxy("bmbox/execute_manual_operation", ExecuteManualOperation)
			manual_operation_payload = String(data = self.__current_manual_operation.get_request())
			response = execute_manual_operation(manual_operation_payload)
			
			if response.result.data:
				
				self.__update_refbox_state(response.refbox_state)
				
				self.__refbox_state_observer.wait_manual_operation_state_transition(from_state = RefBoxState.READY, to_states = [RefBoxState.EXECUTING_MANUAL_OPERATION])
				self.__refbox_state_observer.wait_manual_operation_state_transition(from_state = RefBoxState.EXECUTING_MANUAL_OPERATION, to_states = [RefBoxState.READY])
			
			else:
				rospy.logerr("request_manual_operation: Manual operation FAILED (refbox refused to execute the manual operation)")
				
		
		except rospy.ServiceException, e:
			rospy.logerr("Service call failed: %s" % (e))
		
		### normal post conditions:
		self.__fsm.update(BmBoxState.READY)
		self.__current_manual_operation = None
		return
Beispiel #23
0
def message_handler(bot, update):
    state = database_manager.get_user_state(update.message.chat.id)
    fsm = FSM(state)
    print("state before is: " + fsm.machine.state)
    if update.message.text == 'بازشگت به منو اولیه':
        start(bot, update)
    elif update.message.text == 'اضافه کردن کلاس':
        fsm.machine.add_class(update)
        print("state after is: " + fsm.machine.state)
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)

    elif update.message.text == 'اضافه کردن استاد':
        fsm.machine.add_teacher(update)
        print("state after is: " + fsm.machine.state)
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)

    elif update.message.text == 'درخواست کلاس':
        fsm.machine.get_i(update)  # go to state for getting instractor
        print("state after is: " + fsm.machine.state)
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)

    elif fsm.machine.state == 'new_class':
        parts = update.message.text.split(' ')
        class_description = ''
        for word in parts[2:]:
            class_description += word + ' '
        database_manager.add_class(parts[0], parts[1], class_description)
        fsm.machine.add_class_finished(update, parts[0], parts[1],
                                       class_description)
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)

    elif fsm.machine.state == 'new_teacher':
        parts = update.message.text.split(' ')
        database_manager.add_teacher(parts[0], parts[1])
        fsm.machine.add_teacher_finished(
            update,
            parts[0],
            parts[1],
        )
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)

    elif fsm.machine.state == 'get_class_i':
        temp_map[update.message.chat.id] = [update.message.text]
        fsm.machine.get_w(update)
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)

    elif fsm.machine.state == 'get_class_w':
        temp_map[update.message.chat.id].append(update.message.text)
        fsm.machine.get_t(update)
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)

    elif fsm.machine.state == 'get_class_t':
        temp_map[update.message.chat.id].append(update.message.text)

        taken_class = database_manager.find_and_insert_class(
            temp_map[update.message.chat.id])

        fsm.machine.class_got(
            update,
            taken_class,
            temp_map[update.message.chat.id][0],
            temp_map[update.message.chat.id][1],
            temp_map[update.message.chat.id][2],
        )

        del temp_map[update.message.chat.id]
        database_manager.set_user_state(update.message.chat.id,
                                        fsm.machine.state)
Beispiel #24
0
    mainFile.write("test = SolverForTests(%d, %d)\n" %
                   (fsm.numberOfStates, fsm.numberOfInputs))
    mainFile.write(
        "test.fill_StateCover()\ntest.fill_newStatesDict()\ntest.create_env()\ntest.create_tran_env()\n\ntest.create_formula()\n#test.new_create_transition_formula()\ntest.industrial_transition_formula()\n\n"
    )
    mainFile.write(
        'if (test.solver.check() == z3.sat):\n\tprint("sat")\nelse:\n\tprint ("unsat")\n'
    )
    mainFile.close()


if __name__ == '__main__':
    parser = createParamParser()
    args = parser.parse_args()
    mainFileName = args.mainFile
    fsm = FSM()
    fsm.readFSMfromFile(args.fsmFile)
    # fsm.printTransitionTable()
    (inputs, outputs) = readTestFromFile(args.testFile)
    states = []
    (states, outputs) = fsm.getStatesAndOutputsFromTest(inputs)

    # print ("inp")
    # print (inputs)
    # print ("outp")
    # print (outputs)
    # print ("states")
    # print (states)
    # for i in range(len(inputs)):
    # 	print (str(states[i]) + " " + str(inputs[i]) + "/" + str(outputs[i]))
Beispiel #25
0
def analysis_str(str: str):
    state_machine = FSM()
    for ch in str:
        state_machine.send(ch)
    return state_machine.does_match()
Beispiel #26
0
	@staticmethod
	def FooLeft(data):
		if data == "Left":
			print "trans Left true"
			return True
		return False


	@staticmethod
	def FooNone(data):
		if data == "None":
			print "trans None true"
			return True
		return False

fsm = FSM(StateIDs.Standing)

fsm.addStates()

fsm.addTransition(StateIDs.Standing, StateIDs.StartRunningRight, 
					transReqFns.FooRight)
fsm.addTransition(StateIDs.StartRunningRight, StateIDs.RunningRight, 
					transReqFns.FooRight)
fsm.addTransition(StateIDs.Standing, StateIDs.StartRunningLeft, 
					transReqFns.FooLeft)
fsm.addTransition(StateIDs.StartRunningLeft, StateIDs.RunningLeft, 
					transReqFns.FooLeft)
fsm.addTransition(StateIDs.StartRunningLeft, StateIDs.Standing, 
					transReqFns.FooNone)
fsm.addTransition(StateIDs.StartRunningRight, StateIDs.Standing, 
					transReqFns.FooNone)
 def test_init(self):
     fsm = FSM("start")
     self.assertEqual("start", fsm.current_state)
     self.assertIsNone(fsm.prev_state)
     self.assertIsNone(fsm.action)
     self.assertEqual({}, fsm.transitions)
 def test_add_transition_3args(self):
     fsm = FSM("on")
     fsm.add_transition("change", "on", "radio")
     self.assertEqual(("radio", "on"), fsm.transitions[("change", "on")])
 def test_add_transition_4args(self):
     fsm = FSM("off")
     fsm.add_transition("play", "off", "music", "on")
     self.assertEqual(("music", "on"), fsm.transitions[("play", "off")])
Beispiel #30
0
from FSM import FSM
from KPC_agent import KPC
import pdb


if __name__ == "__main__":
    AGENT = KPC()
    fsm = FSM(AGENT)
    fsm.setup_rules()
    while fsm.run:
        print(fsm.state)
        #print(AGENT.passcode_buffer)
        # pdb.set_trace()
        signal = fsm.get_next_signal()
        fsm.run_rules(signal)
# Logging should be a class lather on - TODO
import logging as log

# filename='app.log', filemode='w',
log.basicConfig(level=log.INFO, format='%(asctime)s - %(levelname)s - %(message)s',
                datefmt='%d-%b-%y %H:%M:%S')

###

from Camera import Camera

# Initializes FSM
from FSM import FSM
fsm = FSM()
# Code smells - any way to do it better? TODO
shouldRun = True
while (shouldRun):
    fsm.next_state()
Beispiel #32
0
class Lion:
    def __init__(self, initial_state):
        self.FSM = FSM(initial_state)

        self.FSM.add_transition("Antelope", "Hungry", "Eat", "Fed")
        self.FSM.add_transition("Antelope", "Fed", "Sleep", "Hungry")
        self.FSM.add_transition("Hunter", "Hungry", "Run away")
        self.FSM.add_transition("Hunter", "Fed", "Run away", "Hungry")
        self.FSM.add_transition("Tree", "Hungry", "Sleep")
        self.FSM.add_transition("Tree", "Fed", "Look", "Hungry")

    def meet(self, who):
        self.FSM.execute(who)