当前位置: 首页>>代码示例>>Python>>正文


Python Fysom.isstate方法代码示例

本文整理汇总了Python中fysom.Fysom.isstate方法的典型用法代码示例。如果您正苦于以下问题:Python Fysom.isstate方法的具体用法?Python Fysom.isstate怎么用?Python Fysom.isstate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在fysom.Fysom的用法示例。


在下文中一共展示了Fysom.isstate方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: FysomStateTests

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]
class FysomStateTests(unittest.TestCase):
    def setUp(self):
        self.fsm = Fysom({
            'initial': 'green',
            'events': [
                {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                {'name': 'clear', 'src': 'yellow', 'dst': 'green'}
            ]
        })

    def test_is_state_should_succeed_for_initial_state(self):
        self.assertTrue(self.fsm.isstate('green'))

    def test_identity_transition_should_not_be_allowed_by_default(self):
        self.assertFalse(self.fsm.can('clear'))
        self.assertTrue(self.fsm.cannot('clear'))

    def test_configured_transition_should_work(self):
        self.assertTrue(self.fsm.can('warn'))

    def test_transition_should_change_state(self):
        self.fsm.warn()
        self.assertTrue(self.fsm.isstate('yellow'))

    def test_should_raise_exception_when_state_transition_is_not_allowed(self):
        self.assertRaises(FysomError, self.fsm.panic)
        self.assertRaises(FysomError, self.fsm.calm)
        self.assertRaises(FysomError, self.fsm.clear)
开发者ID:AFDudley,项目名称:fysom,代码行数:32,代码来源:fysom_state_tests.py

示例2: FysomStateTests

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]
class FysomStateTests(unittest.TestCase):
    def setUp(self):
        self.fsm = Fysom({
            'initial': 'green',
            'events': [
                {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                {'name': 'clear', 'src': 'yellow', 'dst': 'green'},
                {'name': 'warm', 'src': 'green', 'dst': 'blue'}
            ]
        })

    def test_is_state_should_succeed_for_initial_state(self):
        self.assertTrue(self.fsm.isstate('green'))

    def test_identity_transition_should_not_be_allowed_by_default(self):
        self.assertFalse(self.fsm.can('clear'))
        self.assertTrue(self.fsm.cannot('clear'))

    def test_configured_transition_should_work(self):
        self.assertTrue(self.fsm.can('warn'))

    def test_transition_should_change_state(self):
        self.fsm.warn()
        self.assertTrue(self.fsm.isstate('yellow'))

    def test_should_raise_exception_when_state_transition_is_not_allowed(self):
        self.assertRaises(FysomError, self.fsm.panic)
        self.assertRaises(FysomError, self.fsm.calm)
        self.assertRaises(FysomError, self.fsm.clear)

    def test_event_handler_has_name_and_docstring(self):
        self.assertEqual(self.fsm.warm.__name__, "warm", "Event handlers do not have appropriate name.")
        self.assertNotEqual(self.fsm.warm.__name__, None, "Docstring for event handler is None!")

    def test_trigger_should_trigger_the_event_handler(self):
        self.assertEqual(self.fsm.current, "green", "The initial state isn't the expected state.")
        self.fsm.trigger("warm")
        make_callable = lambda: self.fsm.trigger("unknowevent")
        self.assertRaises(FysomError, make_callable)
        self.assertEqual(self.fsm.current, "blue", "The initial state isn't the expected state.")
开发者ID:tanwanirahul,项目名称:fysom,代码行数:44,代码来源:fysom_state_tests.py

示例3: HalrcompSubscribe

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]

#.........这里部分代码省略.........
        if self.debuglevel > 0:
            print('[%s]: event HEARTBEAT TIMEOUT' % self.debugname)
        self.stop_heartbeat_timer()
        self.stop_socket()
        self.start_socket()
        return True

    def _on_fsm_heartbeat_tick(self, _):
        if self.debuglevel > 0:
            print('[%s]: event HEARTBEAT TICK' % self.debugname)
        self.reset_heartbeat_timer()
        return True

    def _on_fsm_any_msg_received(self, _):
        if self.debuglevel > 0:
            print('[%s]: event ANY MSG RECEIVED' % self.debugname)
        self.reset_heartbeat_liveness()
        self.reset_heartbeat_timer()
        return True

    @property
    def error_string(self):
        return self._error_string

    @error_string.setter
    def error_string(self, string):
        if self._error_string is string:
            return
        self._error_string = string
        for cb in self.on_error_string_changed:
            cb(string)

    def start(self):
        if self._fsm.isstate('down'):
            self._fsm.start()

    def stop(self):
        if self._fsm.isstate('trying'):
            self._fsm.stop()
        elif self._fsm.isstate('up'):
            self._fsm.stop()

    def add_socket_topic(self, name):
        self._socket_topics.add(name)

    def remove_socket_topic(self, name):
        self._socket_topics.remove(name)

    def clear_socket_topics(self):
        self._socket_topics.clear()

    def _socket_worker(self, context, uri):
        poll = zmq.Poller()
        socket = context.socket(zmq.SUB)
        socket.setsockopt(zmq.LINGER, 0)
        socket.connect(uri)
        poll.register(socket, zmq.POLLIN)
        # subscribe is always connected to socket creation
        for topic in self._socket_topics:
            socket.setsockopt(zmq.SUBSCRIBE, topic.encode())

        shutdown = context.socket(zmq.PULL)
        shutdown.connect(self._shutdown_uri)
        poll.register(shutdown, zmq.POLLIN)

        while True:
开发者ID:strahlex,项目名称:pymachinetalk,代码行数:70,代码来源:halrcompsubscribe.py

示例4: ErrorBase

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]

#.........这里部分代码省略.........
        self.clear_connected()
        return True

    @property
    def error_string(self):
        return self._error_string

    @error_string.setter
    def error_string(self, string):
        if self._error_string is string:
            return
        self._error_string = string
        for cb in self.on_error_string_changed:
            cb(string)

    @property
    def error_uri(self):
        return self._error_channel.socket_uri

    @error_uri.setter
    def error_uri(self, value):
        self._error_channel.socket_uri = value

    def update_topics(self):
        print('WARNING: slot update topics unimplemented')

    def set_connected(self):
        print('WARNING: slot set connected unimplemented')

    def clear_connected(self):
        print('WARNING: slot clear connected unimplemented')

    def start(self):
        if self._fsm.isstate('down'):
            self._fsm.connect()

    def stop(self):
        if self._fsm.isstate('trying'):
            self._fsm.disconnect()
        elif self._fsm.isstate('up'):
            self._fsm.disconnect()

    def add_error_topic(self, name):
        self._error_channel.add_socket_topic(name)

    def remove_error_topic(self, name):
        self._error_channel.remove_socket_topic(name)

    def clear_error_topics(self):
        self._error_channel.clear_socket_topics()

    def start_error_channel(self):
        self._error_channel.start()

    def stop_error_channel(self):
        self._error_channel.stop()

    # process all messages received on error
    def _error_channel_message_received(self, identity, rx):

        # react to emc nml error message
        if rx.type == pb.MT_EMC_NML_ERROR:
            self.emc_nml_error_received(identity, rx)

        # react to emc nml text message
        elif rx.type == pb.MT_EMC_NML_TEXT:
开发者ID:strahlex,项目名称:pymachinetalk,代码行数:70,代码来源:errorbase.py

示例5: StatesTestCase

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]
class StatesTestCase(unittest.TestCase):
    def setUp(self):
        self.fsm = Fysom({
            'initial': 'green',
            'events': [
                {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                {'name': 'clear', 'src': 'yellow', 'dst': 'green'}
            ]
        })

    def test_invalid_state(self):
        self.assertRaises(AttributeError, getattr, self.fsm, 'wtfbbq')

    def test_state_conditions(self):
        """
        This will check for example, if state is in clear, will be able to emit
        warn and will not be able to emit panic, calm or clear again.
        """
        self.assertTrue(self.fsm.isstate('green'))
        self.assertTrue(self.fsm.can('warn'))
        self.assertFalse(self.fsm.can('panic'))
        self.assertTrue(self.fsm.cannot('panic'))
        self.assertFalse(self.fsm.can('clam'))
        self.assertFalse(self.fsm.can('clear'))

    def test_state_changing(self):
        self.assertTrue(self.fsm.isstate('green'))
        self.fsm.warn()
        self.assertTrue(self.fsm.isstate('yellow'))

    def test_state_cannot_be_called_twice(self):
        self.fsm.warn()
        self.assertTrue(self.fsm.isstate('yellow'))
        self.assertRaises(FysomError, self.fsm.warn)

    def test_auto_next_state(self):
        self.assertEqual('green', self.fsm.current)

        self.assertEqual('yellow', self.fsm.next())
        self.assertEqual('yellow', self.fsm.current)

    def test_multiple_possibilities_for_next(self):
        fsm = Fysom({
            'initial': 'green',
            'events': [
                {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                {'name': 'panic', 'src': 'green', 'dst': 'red'},
                {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                {'name': 'clear', 'src': 'yellow', 'dst': 'green'}
            ]
        })

        self.assertRaises(MultiplePossibilitesFound, fsm.next)

    def test_no_possibility_for_next(self):
        fsm = Fysom({
            'initial': 'green',
            'events': [
                {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                {'name': 'clear', 'src': 'yellow', 'dst': 'green'}
            ]
        })

        self.assertRaises(NoPossibilityFound, fsm.next)

    def test_goto(self):
        fsm = Fysom({
            'initial': 'green',
            'events': [
                {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                {'name': 'panic', 'src': 'green', 'dst': 'red'},
                {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                {'name': 'clear', 'src': 'yellow', 'dst': 'green'}
            ]
        })
        self.assertRaises(MultiplePossibilitesFound, fsm.next)
        self.assertEqual('red', fsm.goto('panic'))

    def test_no_possibility_for_goto(self):
        fsm = Fysom({
            'initial': 'green',
            'events': [
                {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                {'name': 'panic', 'src': 'green', 'dst': 'red'},
                # when call panic from green, we go to red, from red we
                # should go to yellow, but it is commented and we should
                # have a exception
                # {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                {'name': 'clear', 'src': 'yellow', 'dst': 'green'}
            ]
        })

        self.assertRaises(MultiplePossibilitesFound, fsm.next)
        self.assertEqual('red', fsm.goto('panic'))
#.........这里部分代码省略.........
开发者ID:titansgroup,项目名称:fysom,代码行数:103,代码来源:test_states.py

示例6: RpcClient

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]

#.........这里部分代码省略.........
    def _on_fsm_any_msg_sent(self, _):
        if self.debuglevel > 0:
            print('[%s]: event ANY MSG SENT' % self.debugname)
        self.reset_heartbeat_timer()
        return True

    def _on_fsm_stop(self, _):
        if self.debuglevel > 0:
            print('[%s]: event STOP' % self.debugname)
        self.stop_heartbeat_timer()
        self.stop_socket()
        return True

    def _on_fsm_up(self, _):
        if self.debuglevel > 0:
            print('[%s]: state UP' % self.debugname)
        for cb in self.on_state_changed:
            cb('up')
        return True

    @property
    def error_string(self):
        return self._error_string

    @error_string.setter
    def error_string(self, string):
        if self._error_string is string:
            return
        self._error_string = string
        for cb in self.on_error_string_changed:
            cb(string)

    def start(self):
        if self._fsm.isstate('down'):
            self._fsm.start()

    def stop(self):
        if self._fsm.isstate('trying'):
            self._fsm.stop()
        elif self._fsm.isstate('up'):
            self._fsm.stop()

    def _socket_worker(self, context, uri):
        poll = zmq.Poller()
        socket = context.socket(zmq.DEALER)
        socket.setsockopt(zmq.LINGER, 0)
        socket.connect(uri)
        poll.register(socket, zmq.POLLIN)

        shutdown = context.socket(zmq.PULL)
        shutdown.connect(self._shutdown_uri)
        poll.register(shutdown, zmq.POLLIN)
        pipe = context.socket(zmq.PULL)
        pipe.connect(self._pipe_uri)
        poll.register(pipe, zmq.POLLIN)

        while True:
            s = dict(poll.poll())
            if shutdown in s:
                shutdown.recv()
                return  # shutdown signal
            if pipe in s:
                socket.send(pipe.recv(), zmq.NOBLOCK)
            if socket in s:
                self._socket_message_received(socket)
开发者ID:strahlex,项目名称:pymachinetalk,代码行数:69,代码来源:rpcclient.py

示例7: __init__

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]

#.........这里部分代码省略.........
            self.search.reset()
            self.explore.reset()

        self.initialize = Fysom(
            {
                "initial": "init",
                "events": [
                    {"name": "uci", "src": "init", "dst": "stockfish"},
                    {"name": "isready", "src": "stockfish", "dst": "uciok"},
                    {"name": "reset", "src": "uciok", "dst": "init"},
                ],
                "callbacks": {"onstockfish": onstockfish, "onuciok": onuciok},
            }
        )
        self.search = Fysom(
            {
                "initial": "init",
                "events": [
                    {"name": "newgame", "src": "init", "dst": "godepth"},
                    {"name": "searching", "src": "godepth", "dst": "godepth"},
                    {"name": "makemove", "src": "godepth", "dst": "move"},
                    {"name": "searching", "src": "move", "dst": "godepth"},
                    {"name": "newgame", "src": "move", "dst": "godepth"},
                    {"name": "reset", "src": "move", "dst": "init"},
                ],
                "callbacks": {"onnewgame": onnewgame, "onmove": onmove},
            }
        )

        self.explore = Fysom(
            {
                "initial": "init",
                "events": [
                    {"name": "ucinewgame", "src": "init", "dst": "goinfinite"},
                    {"name": "infinite", "src": "goinfinite", "dst": "goinfinite"},
                    {"name": "move", "src": "goinfinite", "dst": "bestmove"},
                    {"name": "infinite", "src": "bestmove", "dst": "goinfinite"},
                    {"name": "ucinewgame", "src": "bestmove", "dst": "goinfinite"},
                    {"name": "mate", "src": "bestmove", "dst": "end"},
                    {"name": "reset", "src": "bestmove", "dst": "init"},
                ],
                "callbacks": {"onucinewgame": onucinewgame, "onbestmove": onbestmove},
            }
        )
        self.boomerang = Fysom(
            {
                "initial": "start",
                "events": [
                    {"name": "startsearch", "src": "start", "dst": "godeeper"},
                    {"name": "restart", "src": "wait", "dst": "start"},
                    {"name": "exploremove", "src": "godeeper", "dst": "explore"},
                    {"name": "exploremove", "src": "explore", "dst": "explore"},
                    {"name": "noMoves", "src": "explore", "dst": "analyze"},
                    {"name": "pause", "src": "analyze", "dst": "wait"},
                ],
                "callbacks": {"ongodeeper": ongodeeper, "onexplore": onexplore, "onwait": onwait},
            }
        )

    def resetGame(self):
        self.gameStatus["startpos"] = "startpos"
        self.gameStatus["moves"] = []
        self.gameStatus["moveDepths"] = {}
        self.gameStatus["fen"] = (True,)
        self.gameStatus["centipawns"] = 0
        self.gameStatus["currentMove"] = 1
        self.gameStatus["startPlayer"] = "w"
        self.gameStatus["player"] = "w"
        self.gameStatus["JSONlines"] = []
        self.gameStatus["JSONcurrentLine"] = {}
        self.gameStatus["JSONmoves"] = []
        self.gameStatus["JSONcurrentMove"] = {}

    def findBoomerang(self, startpos):
        self.resetGame()
        self.gameStatus["startpos"] = startpos
        while True:
            if self.boomerang.isstate("start"):
                res = self.manager.get()
                if re.search("^Stockfish", res):
                    self.initialize.uci(self.gameStatus)
                if re.search("^uciok", res):
                    self.initialize.isready()
                if re.search("^readyok", res):
                    self.boomerang.startsearch(
                        self.movesList, self.movesListCP, self.searchingDepth, self.gameStatus, self.cp
                    )
            elif self.boomerang.isstate("wait"):
                self.initialize.uci(self.gameStatus)
                self.manager.clear()
                self.boomerang.restart()
            elif self.boomerang.isstate("godeeper"):
                self.boomerang.exploremove(
                    self.movesList, self.movesListCP, self.totalMoves, self.exploreDepth, self.gameStatus
                )
            elif self.boomerang.isstate("analyze"):
                break

        self.boomerang.pause()
        return json.dumps(self.gameStatus["JSONlines"])
开发者ID:Nixonite,项目名称:chesscomputer,代码行数:104,代码来源:boomerang_server.py

示例8: gemHandler

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]

#.........这里部分代码省略.........
        :rtype: dict
        """
        data = secsHandler._serializeData(self)
        data.update({'communicationState': self.communicationState.current, 'commDelayTimeout': self.commDelayTimeout, 'reportIDCounter': self.reportIDCounter, 'reportSubscriptions': self.reportSubscriptions})
        return data

    def enable(self):
        """Enables the connection"""
        self.connection.enable()
        self.communicationState.enable()

        self.logger.info("Connection enabled")

    def disable(self):
        """Disables the connection"""
        self.connection.disable()
        self.communicationState.disable()

        self.logger.info("Connection disabled")

    def _onHsmsPacketReceived(self, packet):
        """Packet received from hsms layer

        :param packet: received data packet
        :type packet: :class:`secsgem.hsmsPackets.hsmsPacket`
        """
        message = self.secsDecode(packet)

        if message is None:
            self.logger.info("< %s", packet)
        else:
            self.logger.info("< %s\n%s", packet, message)

        if self.communicationState.isstate('WAIT_CRA'):
            if packet.header.stream == 1 and packet.header.function == 13:
                if self.isHost:
                    self.sendStreamFunction(self.streamFunction(1, 14)({"COMMACK": 1, "DATA": {}}))
                else:
                    self.sendStreamFunction(self.streamFunction(1, 14)({"COMMACK": 1, "DATA": {"MDLN": "secsgem", "SOFTREV": "0.0.3"}}))

                self.communicationState.s1f13received()
            elif packet.header.stream == 1 and packet.header.function == 14:
                self.communicationState.s1f14received()
        elif self.communicationState.isstate('WAIT_DELAY'):
            pass
        elif self.communicationState.isstate('COMMUNICATING'):
            # check if callbacks available for this stream and function
            callback_index = "s" + str(packet.header.stream) + "f" + str(packet.header.function)
            if callback_index in self.callbacks:
                threading.Thread(target=self._runCallbacks, args=(callback_index, packet), name="secsgem_gemHandler_callback_{}".format(callback_index)).start()
            else:
                self._queuePacket(packet)

    def _onHsmsSelect(self):
        """Selected received from hsms layer"""
        self.communicationState.select()

    def _onWaitCRATimeout(self):
        """Linktest time timed out, so send linktest request"""
        self.communicationState.communicationreqfail()

    def _onWaitCommDelayTimeout(self):
        """Linktest time timed out, so send linktest request"""
        self.communicationState.delayexpired()

    def _onStateWaitCRA(self, data):
开发者ID:masonlin,项目名称:secsgem,代码行数:70,代码来源:gemHandler.py

示例9: onanalyze

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]
                break

    boomerang.noMoves()
    
def onanalyze(e):
    manager.end()
    
    
boomerang = Fysom({'initial': 'start',
             'events': [{'name': 'startsearch','src':'start','dst':'godeeper'},
                        {'name': 'exploremove','src':'godeeper','dst':'explore'},
                        {'name': 'exploremove','src':'explore','dst':'explore'},
                        {'name': 'noMoves','src':'explore','dst':'analyze'}],
              'callbacks': {
                  'ongodeeper': ongodeeper,
                  'onexplore': onexplore
                  } })

while True:                      
    if boomerang.isstate("start"):
        res = manager.get()
        if re.search('^Stockfish', res):
            initialize.uci(gameStatus)
        if re.search('^uciok', res):
            initialize.isready()
        if re.search('^readyok', res):
            boomerang.startsearch(movesList, movesListCP, searchingDepth, gameStatus, cp)
    elif boomerang.isstate("godeeper"):
        boomerang.exploremove(movesList, movesListCP, totalMoves, exploreDepth, gameStatus)

开发者ID:Nixonite,项目名称:chesscomputer,代码行数:31,代码来源:boomerang.py

示例10: Fysom

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]
#!/usr/bin/python
from fysom import Fysom

print "Experimenting finite state machine package."
fsm = Fysom({'initial': 'green',
	         'events': [
                 { 'name': 'warn', 'src': 'green', 'dst': 'yellow' },
                 { 'name': 'panic', 'src': 'yellow', 'dst': 'red' },
                 { 'name': 'calm', 'src': 'red', 'dst': 'yellow' },
                 { 'name': 'clear', 'src': 'yellow', 'dst': 'green' }
	         ]})


print "Current state = " + fsm.current
print "Is in state 'red? = %r" % fsm.isstate('red')
print "Is in state 'green? = %r" % fsm.isstate('green')
print "Can fire event %s from state %s? = %r" % ('warn', fsm.current, fsm.can('warn'))
print "Can fire event %s from state %s? = %r" % ('panic', fsm.current, fsm.can('panic'))
print "Can fire event %s from state %s? = %r" % ('clear', fsm.current, fsm.can('clear'))

print ""
print "Firing event warn"
fsm.warn()
print "Current state = " + fsm.current
print "Is in state 'red? = %r" % fsm.isstate('red')
print "Is in state 'green? = %r" % fsm.isstate('green')
print "Can fire event %s from state %s? = %r" % ('warn', fsm.current, fsm.can('warn'))
print "Can fire event %s from state %s? = %r" % ('panic', fsm.current, fsm.can('panic'))
print "Can fire event %s from state %s? = %r" % ('clear', fsm.current, fsm.can('clear'))
开发者ID:SamuelToh,项目名称:2147483647_story_ptr_project,代码行数:31,代码来源:finite_state_machine_experiment.py

示例11: hsmsHandler

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]

#.........这里部分代码省略.........

                # queue packet to notify waiting threads
                self._queuePacket(packet)

            # check if it is a deselect request
            elif packet.header.sType == 0x03:
                # if we are disconnecting send reject else send response
                if self.connection.disconnecting:
                    self.sendRejectRsp(packet.header.system, packet.header.sType, 4)
                else:
                    self.sendDeselectRsp(packet.header.system)
                    # update connection state
                    self.connectionState.deselect()

            elif packet.header.sType == 0x04:
                # update connection state
                self.connectionState.deselect()

                # queue packet to notify waiting threads
                self._queuePacket(packet)

            # check if it is a linktest request
            elif packet.header.sType == 0x05:
                # if we are disconnecting send reject else send response
                if self.connection.disconnecting:
                    self.sendRejectRsp(packet.header.system, packet.header.sType, 4)
                else:
                    self.sendLinktestRsp(packet.header.system)

            else:
                # queue packet if not handeled
                self._queuePacket(packet)
        else:
            if not self.connectionState.isstate("SELECTED"):
                self.logger.info("< %s", packet)
                self.logger.warning("received message when not selected")
                self.connection.send_packet(hsmsPacket(hsmsRejectReqHeader(packet.header.system, packet.header.sType, 4)))

                return True

            # redirect packet to hsms handler
            if hasattr(self, '_onHsmsPacketReceived') and callable(getattr(self, '_onHsmsPacketReceived')):
                self._onHsmsPacketReceived(packet)
            else:
                self.logger.info("< %s", packet)

    def _serializeData(self):
        """Returns data for serialization

        :returns: data to serialize for this object
        :rtype: dict
        """
        return {'address': self.address, 'port': self.port, 'active': self.active, 'sessionID': self.sessionID, 'name': self.name, 'connected': self.connected}

    def enable(self):
        """Enables the connection"""
        self.connection.enable()

    def disable(self):
        """Disables the connection"""
        self.connection.disable()

    def waitforStreamFunction(self, stream, function, is_control=False):
        """Wait for an incoming stream and function and return the receive data

        :param stream: number of stream to wait for
开发者ID:masonlin,项目名称:secsgem,代码行数:70,代码来源:hsmsHandler.py

示例12: __init__

# 需要导入模块: from fysom import Fysom [as 别名]
# 或者: from fysom.Fysom import isstate [as 别名]

#.........这里部分代码省略.........
						onsearch(res, gameStatus)
					if re.search('^bestmove (?P<move>\w+) ', res):
						bestmove = re.search('^bestmove (?P<move>\w+) ', res)
						self.explore.move(bestmove.group('move'), gameStatus, exploreDepth, totalMoves, move)

					if (gameStatus["currentMove"]>=totalMoves):
						break
						
				currentLine = {}
				currentLine["searchingDepth"] = gameStatus["moveDepths"][move]
				currentLine["moves"] = gameStatus["JSONmoves"][:]
				gameStatus["JSONlines"].append(currentLine)
				
			self.boomerang.noMoves()
			
		def onwait(e):
			self.initialize.reset()
			self.search.reset()
			self.explore.reset()
			

		self.initialize = Fysom({'initial': 'init',
				 'events': [{'name': 'uci','src':'init','dst':'stockfish'},
							{'name': 'isready','src':'stockfish','dst':'uciok'},
							{'name': 'reset','src':'uciok','dst':'init'}],
				  'callbacks': {
					  'onstockfish': onstockfish,
					  'onuciok': onuciok } })
		self.search = Fysom({'initial': 'init',
					 'events': [{'name': 'newgame','src':'init','dst':'godepth'},
								{'name': 'searching','src':'godepth','dst':'godepth'},
								{'name': 'makemove','src':'godepth','dst':'move'},
								{'name': 'searching','src':'move','dst':'godepth'},
								{'name': 'newgame','src':'move','dst':'godepth'},
								{'name': 'reset','src':'move','dst':'init'}],
					  'callbacks': {
						  'onnewgame': onnewgame,
						  'onmove': onmove} })

		self.explore = Fysom({'initial': 'init',
					 'events': [{'name': 'ucinewgame','src':'init','dst':'goinfinite'},
								{'name': 'infinite','src':'goinfinite','dst':'goinfinite'},
								{'name': 'move','src':'goinfinite','dst':'bestmove'},
								{'name': 'infinite','src':'bestmove','dst':'goinfinite'},
								{'name': 'ucinewgame','src':'bestmove','dst':'goinfinite'},
								{'name': 'mate','src':'bestmove','dst':'end'},
								{'name': 'reset','src':'bestmove','dst':'init'}],
					  'callbacks': {
						  'onucinewgame': onucinewgame,
						  'onbestmove': onbestmove } })
		self.boomerang = Fysom({'initial': 'start',
					 'events': [{'name': 'startsearch','src':'start','dst':'godeeper'},
								{'name': 'restart','src':'wait','dst':'start'},
								{'name': 'exploremove','src':'godeeper','dst':'explore'},
								{'name': 'exploremove','src':'explore','dst':'explore'},
								{'name': 'noMoves','src':'explore','dst':'analyze'},
								{'name': 'pause', 'src':'analyze','dst':'wait'}],
					  'callbacks': {
						  'ongodeeper': ongodeeper,
						  'onexplore': onexplore,
						  'onwait': onwait
						  } })
	
	def resetGame(self):
		self.gameStatus["startpos"] = 'startpos'
		self.gameStatus["moves"] = []
		self.gameStatus["moveDepths"] = {}
		self.gameStatus["fen"] = True,
		self.gameStatus["centipawns"] = 0
		self.gameStatus["currentMove"] = 1
		self.gameStatus["startPlayer"] = 'w'
		self.gameStatus["player"] = 'w'
		self.gameStatus["JSONlines"] = []
		self.gameStatus["JSONcurrentLine"] = {}
		self.gameStatus["JSONmoves"] = []
		self.gameStatus["JSONcurrentMove"] = {}
	
	def findBoomerang(self, startpos):
		self.resetGame()
		self.gameStatus["startpos"] = startpos
		while True:   
			if self.boomerang.isstate("start"):
				res = self.manager.get()
				if re.search('^Stockfish', res):
					self.initialize.uci(self.gameStatus)
				if re.search('^uciok', res):
					self.initialize.isready()
				if re.search('^readyok', res):
					self.boomerang.startsearch(self.movesList, self.movesListCP, self.searchingDepth, self.gameStatus, self.cp)
			elif self.boomerang.isstate("wait"):
				self.initialize.uci(self.gameStatus)
				self.manager.clear()
				self.boomerang.restart()
			elif self.boomerang.isstate("godeeper"):
				self.boomerang.exploremove(self.movesList, self.movesListCP, self.totalMoves, self.exploreDepth, self.gameStatus)
			elif self.boomerang.isstate("analyze"):
				break
				
		self.boomerang.pause()
		return json.dumps(self.gameStatus["JSONlines"])
开发者ID:M0nd4,项目名称:chesscomputer,代码行数:104,代码来源:boomerang_server.py


注:本文中的fysom.Fysom.isstate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。