Beispiel #1
0
def bot():
    replyStack = list()
    msg_in_json = request.get_json()
    msg_in_string = json.dumps(msg_in_json)
    replyToken = msg_in_json["events"][0]['replyToken']
    userID =  msg_in_json["events"][0]['source']['userId']
    msgType =  msg_in_json["events"][0]['message']['type']
    
    if msgType != 'text':
       reply(replyToken, ['Only text is allowed.'])
       return 'OK', 200
    
    sent = msg_in_json["events"][0]['message']['text'].lower().strip()

    if sent == 'reset':
        filebase.remove_user(userID)
        reply(replyToken, ['ลบข้อมูล State Machine บน firebase แล้ว'])
        return 'OK', 200

    if sent in ['สวัสดี','สวัสดีจ้า','สวัสดีครับ','สวัสดีค่ะ','สวัสดีค้าบ','hello','hi','ทัก']:
        reply(replyToken, ['สวัสดีจ้า :)'])
        return 'OK', 200

    state = StateMachine(push, token=userID)

    all_data = compute(sent)
    this_intention = all_data['intent']
    this_information = all_data['frame']

    state.get_input(this_intention, this_information)

    print("Intent:", this_intention)
    print("IR:", this_information)
    return 'OK', 200
Beispiel #2
0
 def test_is_child_final_true(self):
     m = StateMachine()
     s = m.create_state('final', CompositeState)
     f = s.create_state('sfinal', FinalState)
     s.set_state(f)
     e = Event()
     self.assertTrue(guards.is_child_final(e, s))
Beispiel #3
0
 def checkState1(self, value, info):
     if value['sendNum'] > 5:
         text = u"今天已经给你发送太多的短信了,明天再来吧"
         StateMachine.end(info.user)
     elif self.checkPhoneNum(info.text):
         try:
             user = WeixinUser.objects.get(phone=info.text)
             text = "这个手机号已经被使用了,请使用其他号码"
         except:
             user = None
         if user == None:
             verifyCode = str(random.randint(100000, 1000000))
             ret = send_sms(info.text, u"验证码是%s,15分钟内有效" % verifyCode)
             logger.debug("send sms return %s" % ret)
             value = {
                 'state': 2,
                 'phone': info.text,
                 'verifyCode': verifyCode,
                 "sendTime": time.time(),
                 'sendNum': value['sendNum'] + 1
             }
             self.store(info.user, value)
             text = u'我们已经将验证码发送到%s,请将收到的验证码发送给我们就完成验证,如果2分钟内没有收到短信就请输入“重新发送”,我们将重新给你发送新的验证码,如果想换手机号,就请输入“换手机号”' % info.text
     else:
         text = u"请输入正确的手机号"
     return text
Beispiel #4
0
def test_state_machine_init_method():
    """Basic testing for the State Machine init method
    """
    # Setup
    state_machine = StateMachine()

    # Setup
    def decision():
        return 'state2'

    def decision2():
        return 'state3'

    state1 = State(name="state1",
                   routine_function=fun_routine,
                   decision_function=decision,
                   entry_function=fun_entry,
                   exit_function=fun_exit,
                   is_async=False)

    state2 = State(name="state2",
                   routine_function=fun_routine,
                   decision_function=decision2,
                   entry_function=fun_entry,
                   exit_function=fun_exit,
                   is_async=False)

    state3 = State(name="state3",
                   routine_function=fun_routine,
                   decision_function=decision,
                   is_async=False)

    state_machine.add_states(state3, state2, state1)
    state_machine.initial_state = "state1"
Beispiel #5
0
 def test_is_child_final_false(self):
     m = StateMachine()
     s = m.create_state('final', CompositeState)
     c = s.create_state('s')
     s.set_state(c)
     e = Event()
     self.assertFalse(guards.is_child_final(e, s))
Beispiel #6
0
class MainNode():
    def __init__(self):
        rospy.init_node('default_offboard', anonymous=True)
        self.rate = rospy.Rate(20)
        self.mav1 = Mav("mavros")

        self._command_sub = rospy.Subscriber("pose_command", String,
                                             self._pose_command_callback)

        # wait for FCU connection
        self.mav1.wait_for_connection()
        print("mavs connected")

        self.sm = StateMachine()
        self.sm.set_params(self.mav1)
        self.sm.set_current_state(self.sm.States.TAKE_OFF)

    def loop(self):
        # enter the main loop
        while (True):
            # print "Entered whiled loop"
            self.sm.execute()
            self.rate.sleep()

    def _pose_command_callback(self, topic=String()):
        text = topic.data
        textarr = np.array(text.split(";"))
        arr = textarr.astype(np.float)
        print("new target pose: " + str(arr.tolist()))
        pose = create_setpoint_message_xyz_yaw(arr[0], arr[1], arr[2], arr[3])
        self.mav1.set_target_pose(pose)
        self.mav1.max_speed = 1
        self.sm.set_next_state(self.sm.States.IDLE)
        self.sm.set_current_state(self.sm.States.WAITING_TO_ARRIVE)
        pass
Beispiel #7
0
class Wife(BaseGameEntity):
    def __init__(self, val):
        super().__init__(val)
        self.location = "Home"
        self.peeNeed = 5
        self.cookingStew = False
        self.fsm = StateMachine(self)
        self.fsm.globalState = WifeGlobalState()
        self.fsm.currentState = WifeClean()

    def Update(self):
        self.fsm.Update()

    def NeedToRelief(self):
        return self.peeNeed >= 10

    def CookingStew(self):
        return self.cookingStew

    def HandleMessage(self, telegram):
        return self.fsm.HandleMessage(telegram)

    def logStates(self):
        log(str(self) + " global state: " + str(self.fsm.globalState))
        log(str(self) + " current state: " + str(self.fsm.currentState))
        log(str(self) + " previous state: " + str(self.fsm.previousState))
        log(str(self) + " location: " + self.location)
        log(str(self) + " peeNeed: " + str(self.peeNeed))
        log(str(self) + " cookingStew: " + str(self.cookingStew))
Beispiel #8
0
    def test_trivial_case(self):
        grammar = 'rulename = abc "def"\nabc = "abc"'

        rulename = 'rulename'
        edge = Edge('abc', 'abc')
        edge2 = Edge('def', 'def')
        final_edge = Edge('', FINAL_STATE)
        state = State('abc', edge2, is_automata=True)
        state2 = State('def', final_edge)
        start_state = State(START_STATE, edge)
        final_state = State(FINAL_STATE)
        states = [start_state, state, state2, final_state]
        expected = StateMachine(rulename, states)

        rulename = 'abc'
        sub_edge = Edge('abc', 'abc')
        sub_final_edge = Edge('', FINAL_STATE)
        sub_state = State('abc', sub_final_edge)
        sub_start_state = State(START_STATE, sub_edge)
        sub_final_state = State(FINAL_STATE)
        states = [sub_start_state, sub_state, sub_final_state]
        submachine = StateMachine(rulename, states)

        expected.register_automata(submachine)

        actual = choices_parser.parse_from_string(grammar)

        logger.debug(f'Actual: {actual}')
        logger.debug(f'Expected: {expected}')
        assert_state_machines_equal(actual, expected)
Beispiel #9
0
 def test_is_child_final_false(self):
     m=StateMachine()
     s=m.create_state('final', CompositeState)
     c=s.create_state('s')
     s.set_state(c)
     e=Event()
     self.assertFalse( guards.is_child_final(e, s))
Beispiel #10
0
    def __init__(self):
        # Setting the screen
        self.screen = pygame.display.set_mode(
            (settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT))
        pygame.display.set_caption('Bird')

        # Creating the virtual screen
        self.surface = pygame.Surface(
            (settings.VIRTUAL_WIDTH, settings.VIRTUAL_HEIGHT))

        self.background_x = 0
        self.ground_x = 0

        self.clock = pygame.time.Clock()

        self.state_machine = StateMachine({
            'start': states.StartState,
            'count': states.CountState,
            'play': states.PlayState,
            'score': states.ScoreState,
        })
        self.state_machine.change('start')
        pygame.mixer.music.load('sounds/choco_birds_run.mp3')
        pygame.mixer.music.play(loops=-1)

        settings.GAME_SOUNDS['jump'].set_volume(0.5)
        settings.GAME_SOUNDS['death'].set_volume(0.5)
Beispiel #11
0
class Wife(BaseGameEntity):
    def __init__(self, name, global_state=None, current_state=None):
        BaseGameEntity.__init__(self)

        self._name = name
        self.state_machine = StateMachine(self)
        self.location = None

        self.cooking = False
        self.husband = None

        self.state_machine.global_state = global_state
        self.state_machine.current_state = current_state

    @property
    def name(self):
        return self._name

    def update(self):
        self.state_machine.update()

    def handle_message(self, t):
        self.state_machine.handle_message(t)

    def change_location(self, new_location):
        self.location = new_location

    def say(self, s):
        print('\x1b[0;31;40m' + '{0} : '.format(self.name) + s + '\x1b[0m')
Beispiel #12
0
 def test_is_child_final_true(self):
     m=StateMachine()
     s=m.create_state('final', CompositeState)
     f=s.create_state('sfinal', FinalState)
     s.set_state(f)
     e=Event()
     self.assertTrue( guards.is_child_final(e, s))
class TestTransitionErrorStateMachine(unittest.TestCase):
    def setUp(self):
        self.sm = StateMachine("test_state_machine", ["exit", "__preempted__"])
        self.state1 = TestStateLoop("test1", ["s2", "s3"])
        self.state2 = TestStateLoop("test2", ["s1", "s1"])
        self.state3 = TestStateLoop("test3", ["s1", "exit"])
        self.sm.add_state(self.state1, {"s2": "test2", "s3": "test3"}, initial=True)
        self.sm.add_state(self.state2, {"s1": "test1"})
        self.sm.add_state(self.state3, {"s1": "test1"})

    def test_no_states(self):
        error = None
        try:
            StateMachine("test_state_machine", [])._run()
        except TransitionError as e:
            error = e
        assert error is not None

    def test_transition_doesnt_exist(self):
        error = None
        sm = StateMachine("test_state_machine", ["exit", "__preempted__"])
        state1 = TestState("test1", ["s2"])
        sm.add_state(self.state1, {}, initial=True)
        try:
            sm._run()
        except TransitionError as e:
            error = e
            print(error)
        assert error is not None
Beispiel #14
0
    def setup_state_machine(self):
        # This is where we will initialize states, create a state machine, add
        # state transitions to the state machine, and start the state machine.
        hungup_state = HungUpState(self)
        recording_state = RecordingState(self)
        ending_state = EndingState(self)
        reviewing_state = ReviewingState(self)
        greeting_state = GreetingState(self)

        self.state_machine = StateMachine()
        self.state_machine.add_transition(recording_state,
                                          Event.DTMF_OCTOTHORPE,
                                          reviewing_state)
        self.state_machine.add_transition(recording_state, Event.HANGUP,
                                          hungup_state)
        self.state_machine.add_transition(recording_state, Event.DTMF_STAR,
                                          recording_state)
        self.state_machine.add_transition(reviewing_state, Event.HANGUP,
                                          hungup_state)
        self.state_machine.add_transition(reviewing_state,
                                          Event.DTMF_OCTOTHORPE, ending_state)
        self.state_machine.add_transition(reviewing_state, Event.DTMF_STAR,
                                          recording_state)
        self.state_machine.add_transition(greeting_state, Event.HANGUP,
                                          hungup_state)
        self.state_machine.add_transition(greeting_state,
                                          Event.PLAYBACK_COMPLETE,
                                          recording_state)
        self.state_machine.start(greeting_state)
Beispiel #15
0
 def __init__(self, val):
     super().__init__(val)
     self.location = "Home"
     self.peeNeed = 5
     self.cookingStew = False
     self.fsm = StateMachine(self)
     self.fsm.globalState = WifeGlobalState()
     self.fsm.currentState = WifeClean()
 def setUp(self):
     self.sm = StateMachine("test_state_machine", ["exit", "__preempted__"])
     self.state1 = TestStateLoop("test1", ["s2", "s3"])
     self.state2 = TestStateLoop("test2", ["s1", "s1"])
     self.state3 = TestStateLoop("test3", ["s1", "exit"])
     self.sm.add_state(self.state1, {"s2": "test2", "s3": "test3"}, initial=True)
     self.sm.add_state(self.state2, {"s1": "test1"})
     self.sm.add_state(self.state3, {"s1": "test1"})
Beispiel #17
0
    def test_is_final_state_using_subclass(self):
        class AnotherFinalState(FinalState):
            pass

        m = StateMachine()
        s = m.create_state('final', AnotherFinalState)
        e = Event()
        self.assertTrue(guards.is_final_state(e, s))
Beispiel #18
0
    def test_add_transition_to(self):
        m  = StateMachine()
        s1 = m.create_state(name='s1')
        s2 = m.create_state(name='s2')

        s1.add_transition_to(s2, 'test event...')

        self.assertEqual( s2, s1.transitions_by_trigger['test event...'][0].target )
Beispiel #19
0
    def setUp(self):

        chatbot = StateMachine('chatbot')
        active_state = chatbot.create_state('active', CompositeState)
        sleeping_state = chatbot.create_state('sleeping', State)
        final_state = chatbot.create_state('final', FinalState)

        chatbot.initial_state=active_state
        active_state.add_transition_to(sleeping_state, 'sunset')
        active_state.add_transition_to(final_state, 'bandwidth exceeded')

        sleeping_state.add_transition_to(active_state, 'sunrise')
        sleeping_state.add_transition_to(final_state, 'power off')

        def become_happy( event, state ):
            state.logger.info('Becoming Happy')

        def happy_message(event, state):
            if event.name=='msg':
                state.logger.info('Hello %s, I am happy', event.payload['from'])

        def become_sad(event, state):
            state.logger.info('Becoming Sad')

        def sad_message(event, state):
            if event.name=='msg':
                state.logger.info('Hello %s, I am sad', event.payload['from'])

        def sun_is_shining(event, state):
            return True

        def clouds_are_looming(event, state):
            return True

        def do_happy_dance(event, state):
            return True

        def hang_head_in_shame(event, state):
            return True

        happy_state = active_state.create_state('happy')
        happy_state.on_start = become_happy
        happy_state.on_run   = happy_message

        sad_state = active_state.create_state('sad')
        sad_state.on_start = become_sad
        sad_state.on_run = sad_message

        final_state = active_state.create_state( 'depressed', FinalState )

        happy_state.add_transition_to(sad_state, 'criticism', guard=clouds_are_looming, action=hang_head_in_shame)
        sad_state.add_transition_to(happy_state, 'praise', guard=sun_is_shining, action=do_happy_dance)
        sad_state.add_transition_to(final_state, 'excessive criticism')

        active_state.initial_state=happy_state
        active_state.initialise()

        self.chatbot = chatbot
class MainNode():
    def __init__(self):
        rospy.init_node('default_offboard', anonymous=True)
        self.rate = rospy.Rate(20)
        self.mav1 = Mav("uav1/mavros")
        self.mav2 = Mav("uav2/mavros")
        self.sm = StateMachine()
        self.sm.set_params((self.mav1, self.mav2))

        self._command_sub = rospy.Subscriber("pose_command", String,
                                             self._pose_command_callback)

        # wait for FCU connection
        self.mav1.wait_for_connection()
        self.mav2.wait_for_connection()

        self.last_request = rospy.Time.now() - rospy.Duration(5.0)

        self.sm.set_current_state(self.sm.States.TAKE_OFF)

    def loop(self):
        # enter the main loop
        while (True):
            # print "Entered whiled loop"
            self.arm_and_set_mode()
            self.sm.execute()
            self.rate.sleep()

    def arm_and_set_mode(self):
        if rospy.Time.now() - self.last_request > rospy.Duration(1.0):
            if self.mav1.UAV_state.mode != "OFFBOARD":
                self.mav1.set_mode(0, 'OFFBOARD')
                print("enabling offboard mode")
                self.last_request = rospy.Time.now()
            if not self.mav1.UAV_state.armed:
                if self.mav1.set_arming(True):
                    print("Vehicle armed")
                self.last_request = rospy.Time.now()
            if self.mav2.UAV_state.mode != "OFFBOARD":
                self.mav2.set_mode(0, 'OFFBOARD')
                print("enabling offboard mode")
                self.last_request = rospy.Time.now()
            if not self.mav2.UAV_state.armed:
                if self.mav2.set_arming(True):
                    print("Vehicle armed")
                self.last_request = rospy.Time.now()

    def _pose_command_callback(self, topic=String()):
        text = topic.data
        textarr = np.array(text.split(";"))
        arr = textarr.astype(np.float)
        print("new target pose: " + str(arr.tolist()))
        pose = create_setpoint_message_xyz_yaw(arr[0], arr[1], arr[2], arr[3])
        self.mav1.set_target_pose(pose)
        self.mav2.set_target_pose(pose)
        self.sm.set_next_state(self.sm.States.IDLE)
        self.sm.set_current_state(self.sm.States.WAITING_TO_ARRIVE)
        pass
Beispiel #21
0
    def test_start_stores_event(self):

        m = StateMachine()
        s = m.create_state(name='test state')

        e = Event()
        s.start(e)

        self.assertEqual(e, s.start_event)
    def test_without_test_bank(self):
        state_machine = StateMachine()
        search = Mock()
        state_machine._search = search

        response = state_machine._handle(0, new_question_message)

        assert response is None
        search.get_search_results.assert_called_with(question)
 def setUp(self):
     self.iterations_num = 3
     self.sm = StateMachine("test_state_machine", ["exit", "__preempted__"])
     self.state1 = TestState("test1", ["s2", "s3"], execute_iterations=self.iterations_num)
     self.state2 = TestState("test2", ["s3", "s1"], execute_iterations=self.iterations_num)
     self.state3 = TestState("test3", ["exit", "s1"], execute_iterations=self.iterations_num)
     self.sm.add_state(self.state1, {"s2": "test2", "s3": "test3"}, initial=True)
     self.sm.add_state(self.state2, {"s1": "test1", "s3": "test3"})
     self.sm.add_state(self.state3, {"s2": "test2", "s1": "test1"})
Beispiel #24
0
    def test_is_final_state_using_subclass(self):

        class AnotherFinalState(FinalState):
            pass

        m = StateMachine()
        s = m.create_state('final', AnotherFinalState)
        e = Event()
        self.assertTrue( guards.is_final_state(e, s) )
Beispiel #25
0
    def test_add_transition_to(self):
        m = StateMachine()
        s1 = m.create_state(name='s1')
        s2 = m.create_state(name='s2')

        s1.add_transition_to(s2, 'test event...')

        self.assertEqual(s2,
                         s1.transitions_by_trigger['test event...'][0].target)
Beispiel #26
0
    def test_start_stores_event(self):

        m = StateMachine()
        s = m.create_state(name='test state')

        e = Event()
        s.start(e)

        self.assertEqual(e, s.start_event)
Beispiel #27
0
    def __init__(self):

        # getting access to elements in DroneVideo and FlightstatsReciever
        super(DroneMaster, self).__init__()

        self.objectName = "Test Object"
        self.startingAngle = 0
        self.circleRadius = 1  #meters
        self.circlePoints = 8  #numbers of points equally spaced along circle
        self.startTime = 0
        # backpack: 120/-55/95
        # +100 for big objects, +50 for shorter objects. (Modifies how close drone is to object; smaller # > closer)
        # +10 for very small objects.
        self.yOffset = 0
        # -30 for big objects, -15 for shorter objects. (Modifies how close drone is to object; larger # > closer)
        self.ySizeOffset = -30
        # +75 for tall objects or using cube, 0 for shorter objects. (Modifies how high the drone should fly; smaller # > lower
        self.zOffset = 25

        # Seting up a timestamped folder inside Flight_Info that will have the pictures & log of this flight
        self.droneRecordPath = (
            expanduser("~") +
            "/drone_ws/src/SVCL_ardrone_automation/src/Flight_Info/" +
            self.objectName + "_Flight_" +
            datetime.datetime.now().strftime("%m-%d-%Y__%H:%M:%S, %A") + "/")
        if not os.path.exists(self.droneRecordPath):
            os.makedirs(self.droneRecordPath)
        #self.logger = Logger(self.droneRecordPath, "AR Drone Flight")
        #self.logger.Start()

        #import PID and color constants
        self.settingsPath = expanduser(
            "~"
        ) + "/drone_ws/src/SVCL_ardrone_automation/src/resources/calibrater_settings.txt"

        # initalizing the state machine that will handle which algorithms to run at which time;
        # the results of the algorithms will be used to control the drone
        self.stateMachine = StateMachine()

        # drone starts without any machine loaded, so that it can be controlled using the keyboard
        self.currMachine = None

        # i1nitalizing helper objects
        self.pictureManager = PictureManager(self.droneRecordPath)
        self.controller = BasicDroneController("TraceCircle")
        self.startTimer = time.clock()
        # max height of drone, in mm; any higher and the drone will auto-land
        self.maxHeight = 2530
        self.emergency = False
        self.captureRound = 0.5
        self.oldBattery = -1
        self.photoDirective = CapturePhotoDirective(self.droneRecordPath, 30,
                                                    0.014, self.objectName,
                                                    self.circlePoints, 1000, 0)
        self.keySub = rospy.Subscriber('/controller/keyboard', ROSString,
                                       self.keyPress)
Beispiel #28
0
    def test_add_transition_to_without_params(self):
        m  = StateMachine()
        m.logger.info(m.states)
        s1 = m.create_state(name='s1')
        s2 = m.create_state(name='s2')

        s1.add_transition_to(s2)

        self.assertEqual( 0, len( s1.transitions_by_trigger ) )
        self.assertEqual( s2, s1.default_transition.target )
Beispiel #29
0
    def test_notify_observers(self):
        m = StateMachine()
        m.notify_observers = MagicMock()
        s = State('test state', m)

        e = Event()
        s.notify_observers(e)

        self.assertEqual(1, m.notify_observers.call_count)
        self.assertEqual(e, m.notify_observers.call_args[0][0])
Beispiel #30
0
    def test_add_transition_to(self):
        m   = StateMachine()
        ps  = m.create_state('ps', PseudoState)
        tgt1 = m.create_state('tgt1')

        g1 = lambda event, state: True
        ps.add_transition_to(tgt1, guard=g1)

        self.assertEqual(1, len(ps.transitions))
        self.assertEqual(tgt1, ps.transitions[0].target)
Beispiel #31
0
    def test_add_transition_to_without_params(self):
        m = StateMachine()
        m.logger.info(m.states)
        s1 = m.create_state(name='s1')
        s2 = m.create_state(name='s2')

        s1.add_transition_to(s2)

        self.assertEqual(0, len(s1.transitions_by_trigger))
        self.assertEqual(s2, s1.default_transition.target)
Beispiel #32
0
 def __init__(self, val):
     super().__init__(val)
     self.location = "Mine"
     self.moneyInBank = 10
     self.goldCarried = 19
     self.thirst = 0
     self.fatigue = 10
     self.fsm = StateMachine(self)
     self.fsm.globalState = MinerGlobalState()
     self.fsm.currentState = MineForGold()
Beispiel #33
0
    def test_add_transition_to(self):
        m = StateMachine()
        ps = m.create_state('ps', PseudoState)
        tgt1 = m.create_state('tgt1')

        g1 = lambda event, state: True
        ps.add_transition_to(tgt1, guard=g1)

        self.assertEqual(1, len(ps.transitions))
        self.assertEqual(tgt1, ps.transitions[0].target)
Beispiel #34
0
    def test_notify_observers(self):
        m = StateMachine()
        m.notify_observers = MagicMock()
        s = State('test state', m)

        e = Event()
        s.notify_observers(e)

        self.assertEqual(1, m.notify_observers.call_count)
        self.assertEqual(e, m.notify_observers.call_args[0][0])
Beispiel #35
0
 def test_undispach_event(self):
     sm_test = StateMachine()
     sm_test.sm['load'] = {1: print("test")}
     sm_test.inicia_tread()
     sm_test.on_event(event=1, args=None)
     sm_test.finaliza_tread()
     assert 1 == sm_test.events_queue.getLenth()
    def test_notify_child(self):
        m = StateMachine()

        composite_state = m.create_state('composite', CompositeState)
        target_state = m.create_state('target')
        composite_state.add_transition_to(target_state, 'tick')

        substate_source = composite_state.create_state('substate1')
        substate_target = composite_state.create_state('substate2')
        substate_source.add_transition_to(substate_target, 'tick')

        substate_source.on_end = MagicMock()
        substate_target.on_start = MagicMock()

        composite_state.initial_state = substate_source
        composite_state.initialise()

        m.initial_state = composite_state
        m.initialise()

        # Test, expecting the composite state's machine to transition
        e = Event('tick')
        m.notify(e)

        # Verify
        self.assertEqual(composite_state, m.current_state)
        self.assertEqual(substate_target, composite_state.current_state)
        self.assertEqual(1, substate_source.on_end.call_count)
        self.assertEqual(1, substate_target.on_start.call_count)
Beispiel #37
0
class Game(object):
    """ This is where the main gameloop runs.
        :param machine = Creates an instance of StateMachine."""

    def __init__(self):

        pygame.init()
        self.machine = StateMachine()
        self.display_w = 800
        self.display_h = 600

    def run(self):

        self.display = pygame.display.set_mode((self.display_w,self.display_h))
        pygame.display.set_caption('The DiceGame')
        self.clock = pygame.time.Clock()

        self.machine.load(intro_state.IntroState(self.machine, self.display))

        while self.machine.isRunning():

            self.machine.nextState()
            self.machine.update()
            self.machine.draw()
            self.clock.tick(30)
            # Debug
            if (len(self.machine.states) > 1):
                print("Machinestates: '{}'".format(self.machine.states))

        print("")
        print("----------------")
        print("DiceGame succesfully terminated.")
        print("Now clearing pygame.")
        print("")
        pygame.quit()
Beispiel #38
0
    def test_to_str(self):

        m = StateMachine()
        s = m.create_state(name='test state')

        s2 = m.create_state(name='s2')
        s.add_transition_to( s2, 'trigger' )

        r = s.transitions[0].to_str()

        self.assertEqual('trigger', r)
Beispiel #39
0
    def test_to_str(self):

        m = StateMachine()
        s = m.create_state(name='test state')

        s2 = m.create_state(name='s2')
        s.add_transition_to(s2, 'trigger')

        r = s.transitions[0].to_str()

        self.assertEqual('trigger', r)
    def __init__(self, *args, **kwargs):
        super(TestStringPattern, self).__init__(*args, **kwargs)

        self.m = StateMachine()
        self.m.add_state("start_state", state_zero)
        self.m.add_state("first_state", state_one)
        self.m.add_state("second_state", state_two)
        self.m.add_state("third_state", state_three)
        self.m.add_state("last_state", None, end_state=1)
        self.m.add_state("error_state", None, end_state=1)
        self.m.set_start("start_state")
Beispiel #41
0
    def __init__(self, name, global_state=None, current_state=None):
        BaseGameEntity.__init__(self)

        self._name = name
        self.state_machine = StateMachine(self)
        self.location = None

        self.cooking = False
        self.husband = None

        self.state_machine.global_state = global_state
        self.state_machine.current_state = current_state
Beispiel #42
0
	def __init__(self, name='motion', context=None, speed=100.):
		'''
    Parameters:

    name : str
        Name of the underlying Object.
    context : Context instance
        Attach the underlying StateMachine to this context.
    speed : float
        Speed in world-coordinate metric per seconds.
		'''
		StateMachine.__init__(self, name, context)
		self._speed = speed
Beispiel #43
0
	def __init__(self, name='sprite', context=None, layer=1):
		'''
    name:  name of the sprite
    layer: (default: 1 since 0 is reserved for background)
		'''
		StateMachine.__init__(self, name, context)
		if context is None: context = Config.get_default_context()
		context.add_visible_data(self, layer)
		self._layer = layer
		self._location = np.zeros(2)
		self._size = np.zeros(2)
		self._bb_center = np.zeros(2)
		self.set_motion(no_motion)
Beispiel #44
0
    def test_transitions(self):

        m = StateMachine()
        s = m.create_state(name='test state')

        s2 = m.create_state(name='s2')
        s3 = m.create_state(name='s3')

        s.add_transition_to( s2, 'ignore' )
        s.add_transition_to( s3, 'trigger' )

        transitions = s.transitions

        self.assertIsInstance( transitions, list )
        self.assertEqual(2, len( transitions ))
Beispiel #45
0
    def test_transition_to_default(self):

        m = StateMachine()
        s = m.create_state(name='test state')

        s2 = m.create_state(name='should get here')
        s3 = m.create_state(name='should not get here')

        s.add_transition_to(s3, 'test event')
        s.add_transition_to(s2)

        event  = Event('any event')
        t      = s.next_transition(event)

        self.assertEqual(s2, t.target)
Beispiel #46
0
    def test_next_transition(self):

        m = StateMachine()
        s = m.create_state(name='test state')

        s2 = m.create_state(name='s2')
        s3 = m.create_state(name='s3')

        s.add_transition_to( s2, 'ignore' )
        s.add_transition_to( s3, 'trigger' )

        event  = Event('trigger')
        result = s.next_transition( event )

        self.assertEqual(s3, result.target )
Beispiel #47
0
    def test_next_transition(self):

        m   = StateMachine()
        ps  = m.create_state('ps', PseudoState)
        tgt1 = m.create_state('tgt1')
        tgt2 = m.create_state('tgt2')

        g1 = lambda event, state: True
        ps.add_transition_to(tgt1, guard=g1)

        g2 = lambda event, state: False
        ps.add_transition_to(tgt2, guard=g2)

        e = Event()
        t = ps.next_transition(e)
        self.assertEqual(tgt1, t.target)
    def setup_state_machine(self):
        """ setup the states and start the initial state """
        main_menu = DtmfMenuState(self, 'sound:/telewall/sounds/de/mainmenu', allowed_keys=['1', '2', '3'])
        playback = PlaybackRefusedState(self)
        recording_instruction = GenericPlaybackState(self, 'sound:/telewall/sounds/de/record-announcement-instruction')
        recording = RecordingState(self)
        recording_reset = ResetRecordingState(self)
        recording_reset_done = GenericPlaybackState(self, 'sound:/telewall/sounds/de/reset-announcement-done')
        hungup_state = HungUpState(self)
        ending_state = EndingState(self)

        self.state_machine = StateMachine()
        self.state_machine.add_transition(main_menu, Event.DTMF_1, playback)
        self.state_machine.add_transition(main_menu, Event.DTMF_2, recording_instruction)
        self.state_machine.add_transition(main_menu, Event.DTMF_3, recording_reset)

        # 1: playback
        self.state_machine.add_transition(playback, Event.PLAYBACK_COMPLETE, ending_state)

        # 2: recording
        self.state_machine.add_transition(recording_instruction, Event.PLAYBACK_COMPLETE, recording)

        # 3: reset recording
        self.state_machine.add_transition(recording_reset, Event.ACTION_COMPLETE, recording_reset_done)
        self.state_machine.add_transition(recording_reset_done, Event.PLAYBACK_COMPLETE, main_menu)

        # hangup event is in every state
        for state in [main_menu, playback, recording_instruction, recording, recording_reset,
                      recording_reset_done]:
            self.state_machine.add_transition(state, Event.HANGUP, hungup_state)

        self.state_machine.start(main_menu)
Beispiel #49
0
    def setup_state_machine(self):
        """ setup the states and start the initial state """
        check_caller = CheckCallerState(self)
        call_handset = CallHandsetState(self)
        playback_refused = PlaybackRefusedState(self, hangup_caller_when_hangup_handset=False)
        call_connected = CallConnectedState(self)

        hungup_state = HungUpState(self)
        ending_state = EndingState(self)

        self.state_machine = StateMachine()

        # identification
        self.state_machine.add_transition(check_caller, Event.CALLER_ALLOWED, call_handset)
        self.state_machine.add_transition(check_caller, Event.CALLER_REFUSED, playback_refused)

        # allowed
        self.state_machine.add_transition(call_handset, Event.ANSWER, call_connected)
        self.state_machine.add_transition(call_handset, Event.BUSY, ending_state)
        self.state_machine.add_transition(call_connected, Event.CALLER_REFUSED, playback_refused)

        # refused
        self.state_machine.add_transition(playback_refused, Event.PLAYBACK_COMPLETE, ending_state)

        # hangup event is in every state (except the final states hangup and ending)
        for state in [check_caller, call_handset, playback_refused, playback_refused, call_connected]:
            self.state_machine.add_transition(state, Event.HANGUP, hungup_state)

        self.state_machine.start(check_caller)
Beispiel #50
0
 def __init__(self, header_row_fn=None, body_row_fn=None, footer_row_fn=None):
     HTMLParser.__init__(self)
     self.state_machine = StateMachine()
     self.header_row_fn = header_row_fn
     self.body_row_fn = body_row_fn
     self.footer_row_fn = footer_row_fn
     self.cells = []
Beispiel #51
0
class FindBallState(State):
    def __init__(self, worldWrapper):
        # Create our internal state machine
        self.stateMachine = StateMachine(DriveStraightState(worldWrapper))

    def step(self, worldWrapper):
        world = worldWrapper.world

        # Do the global checks
        # newState, changed = self.checkGlobal(worldWrapper)
        # if changepd == STATE_CHANGE_FLAG:
            # return newState, changed

        # If we see any balls
        # Step the state machine
        self.stateMachine.step(worldWrapper)
        return self, self.stateMachine.goal
Beispiel #52
0
    def test_to_str2(self):

        def guard_fn(event, state):
            return True

        def action_fn(event, state):
            pass

        m = StateMachine()
        s = m.create_state(name='test state')

        s2 = m.create_state(name='s2')
        s.add_transition_to( s2, 'trigger', guard=guard_fn, action=action_fn )

        r = s.transitions[0].to_str()

        self.assertEqual('trigger[guard_fn]/action_fn', r)
Beispiel #53
0
class TableParser(HTMLParser):
    VALID_TAGS = ['table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td']

    def __init__(self, header_row_fn=None, body_row_fn=None, footer_row_fn=None):
        HTMLParser.__init__(self)
        self.state_machine = StateMachine()
        self.header_row_fn = header_row_fn
        self.body_row_fn = body_row_fn
        self.footer_row_fn = footer_row_fn
        self.cells = []
        
    def handle_starttag(self, tag, attrs):
        if tag not in TableParser.VALID_TAGS:
            return
        self.state_machine.transition(tag, StateMachine.START_TAG)
    
    def handle_endtag(self, tag):
        if tag not in TableParser.VALID_TAGS:
            return
        self.state_machine.transition(tag, StateMachine.END_TAG)
        if tag == 'tr':
            if self.state_machine.in_header() and self.header_row_fn:
                self.header_row_fn(self.cells)
            elif self.state_machine.in_footer() and self.footer_row_fn:
                self.footer_row_fn(self.cells)
            elif self.body_row_fn:
                self.body_row_fn(self.cells)
            self.cells = []

    def handle_data(self, data):
        if self.state_machine.in_cell():
            self.cells.append(data)
Beispiel #54
0
 def checkState1(self, value, info):
     if value['sendNum'] > 5:
         text = u"今天已经给你发送太多的短信了,明天再来吧"
         StateMachine.end(info.user)
     elif self.checkPhoneNum(info.text):
         try:
             user = WeixinUser.objects.get(phone=info.text)
             text = "这个手机号已经被使用了,请使用其他号码"
         except:
             user = None
         if user == None:
             verifyCode = str(random.randint(100000, 1000000))
             ret = send_sms(info.text, u"验证码是%s,15分钟内有效" % verifyCode)
             logger.debug("send sms return %s" % ret)
             value = {'state':2, 'phone':info.text, 'verifyCode':verifyCode, "sendTime":time.time(), 'sendNum':value['sendNum'] + 1}
             self.store(info.user, value)
             text = u'我们已经将验证码发送到%s,请将收到的验证码发送给我们就完成验证,如果2分钟内没有收到短信就请输入“重新发送”,我们将重新给你发送新的验证码,如果想换手机号,就请输入“换手机号”' % info.text
     else:
         text = u"请输入正确的手机号"
     return text
Beispiel #55
0
class BallAcquisitionState(State):

    TIMEOUT = 10

    def __init__(self, worldWrapper):
        # Create and keep track of our state machine
        self.stateMachine = StateMachine(SeekBallState(worldWrapper))
        # Keep track of time for a timeout
        self.lastTime = time.time()

    def step(self, worldWrapper):
        world = worldWrapper.world

        # Check globals
        newState, changed = self.checkGlobal(worldWrapper)
        if changed == STATE_CHANGE_FLAG:
            return newState, changed


        # Check for a timeout
        if time.time() - self.lastTime > self.TIMEOUT:
            return EscapeState(worldWrapper), STATE_CHANGE_FLAG

        # Check for having lost all the balls
        if len(world.balls) == 0:
            return FindBallState(worldWrapper), STATE_CHANGE_FLAG

        # TODO: run the Ferrous

        # Otherwise, step the state machine
        oldState = self.stateMachine.state
        self.stateMachine.step(worldWrapper)
        # Update our timer
        if self.stateMachine.state != oldState:
            self.lastTime = time.time()

        # Step the state machine
        self.stateMachine.step(worldWrapper)
        return self, self.stateMachine.goal
Beispiel #56
0
 def checkState2(self, value, info):
     if info.text == str(value['verifyCode']):
         StateMachine.end(info.user)
         user = WeixinUser.objects.filter(uid=info.user)[0]
         user.phone = value['phone']
         user.save()
         text = u'恭喜您,已经完成了验证,赶快回复“礼品”去积分商城选择礼品吧'
     elif info.text == u"重新发送":
         if time.time() < value['sendTime'] + 2 * 60:
             text = u"刚给您发送了短信,请耐心等候"
         elif value['sendNum'] > 5:
             text = u"今天已经给您发送了太多短信了,请明天再来吧"
             self.timeout = 12 * 3600
             self.store(info.user, value)
         else:
             verifyCode = str(random.randint(100000, 1000000))
             value['verifyCode'] = verifyCode
             ret = send_sms(value['phone'], u"验证码是%s,15分钟内有效" % verifyCode)
             logger.debug("send sms return %s" % ret)
             value['sendTime'] = time.time()
             value['sendNum'] += 1
             self.store(info.user, value)
             text = u"已经给您发送了一条短信,请查收"
     elif info.text == u"换手机号" or info.text == u"换手机":
         if time.time() < value['sendTime'] + 2 * 60:
             text = u'刚给你发送了短信,请2分钟后没收到,再“换手机号”'
         elif value['sendNum'] > 5:
             text = u'今天已经给你发送了太多短信了,请明天再来吧'
             self.timeout = 12 * 3600
             self.store(info.user, value)
         else:
             value['state'] = 1
             self.store(info.user, value)
             text = u"请输入新的手机号"
     else:
         text = u"您输入的验证码有误,请再看一下"
     return text
Beispiel #57
0
    def __init__(self, testblock_name, metrics):

        self.testblock_name = testblock_name
        rospy.Subscriber("/atf/" + self.testblock_name + "/Trigger", Trigger, self.trigger_callback)

        self.transition = None
        self.metrics = metrics

        self.m = StateMachine(self.testblock_name)
        self.m.add_state(Status.PURGED, self.purged_state)
        self.m.add_state(Status.ACTIVE, self.active_state)
        self.m.add_state(Status.PAUSED, self.paused_state)
        self.m.add_state(Status.FINISHED, self.finished_state, end_state=True)
        self.m.add_state(Status.ERROR, self.error_state, end_state=True)
        self.m.set_start(Status.PURGED)

        self.m.run()
Beispiel #58
0
    def setup_state_machine(self):
        """ setup the states and start the initial state """
        unblock = UnblockState(self, self.dialed_extension)
        done = GenericPlaybackState(self, 'sound:/telewall/sounds/de/unblock-done')
        invalid = GenericPlaybackState(self, 'sound:/telewall/sounds/de/phonenumber-invalid')
        hungup_state = HungUpState(self)
        ending_state = EndingState(self)

        self.state_machine = StateMachine()

        self.state_machine.add_transition(unblock, Event.ACTION_COMPLETE, done)
        self.state_machine.add_transition(unblock, Event.INVALID_INPUT, invalid)

        self.state_machine.add_transition(done, Event.PLAYBACK_COMPLETE, ending_state)
        self.state_machine.add_transition(invalid, Event.PLAYBACK_COMPLETE, ending_state)

        # hangup event is in every state
        for state in [unblock, done, invalid]:
            self.state_machine.add_transition(state, Event.HANGUP, hungup_state)

        self.state_machine.start(unblock)
Beispiel #59
0
def main():
   sm = StateMachine()
   sm.register(state_no_match)
   sm.register(state_one_match)
   sm.register(state_both_match)

   some_string = "hello and welcome to you"
   initial_state = State()
   print sm.evaluate(initial_state, some_string)
   current_state = State()
   some_string_2 = "you and welcome to hello"
   print sm.evaluate(current_state, some_string_2)
Beispiel #60
0
class UnblockCall(BaseAsteriskAppCall):
    """ unblockes a caller using asterisk. A new instance is created for each call.   """

    def __init__(self, ari_client, channel, asterisk_app_name, dialed_extension):
        """
        :param ari_client: the ari client instance
        :param channel: the active channel with the handset
        """
        super(UnblockCall, self).__init__(ari_client, channel, asterisk_app_name)
        self.dialed_extension = dialed_extension
        self.state_machine = None
        self.setup_state_machine()

    def setup_state_machine(self):
        """ setup the states and start the initial state """
        unblock = UnblockState(self, self.dialed_extension)
        done = GenericPlaybackState(self, 'sound:/telewall/sounds/de/unblock-done')
        invalid = GenericPlaybackState(self, 'sound:/telewall/sounds/de/phonenumber-invalid')
        hungup_state = HungUpState(self)
        ending_state = EndingState(self)

        self.state_machine = StateMachine()

        self.state_machine.add_transition(unblock, Event.ACTION_COMPLETE, done)
        self.state_machine.add_transition(unblock, Event.INVALID_INPUT, invalid)

        self.state_machine.add_transition(done, Event.PLAYBACK_COMPLETE, ending_state)
        self.state_machine.add_transition(invalid, Event.PLAYBACK_COMPLETE, ending_state)

        # hangup event is in every state
        for state in [unblock, done, invalid]:
            self.state_machine.add_transition(state, Event.HANGUP, hungup_state)

        self.state_machine.start(unblock)