def __init__(self):

        self._config: dict
        self.clients: list
        self._server_socket: socket.socket
        self.db_connector: Connector
        self.is_running: bool
        self._sel: selectors.DefaultSelector
        self.lock_clients: threading.RLock

        self._config = None
        self.clients = None
        self._server_socket = None
        self.db_connector = None
        self.is_running = False

        self._sel = None

        self.lock_clients = threading.RLock()

        EventManager.register_handler(CONNECT_CLIENT_EVENT,
                                      self._handle_connect_client)
        EventManager.register_handler(DISCONNECTED_CLIENT_EVENT,
                                      self._handle_disconnect_client)

        signal.signal(signal.SIGINT, self.stop)
    def _accept_client(self):
        channel: socket.socket
        address: tuple

        channel, address = self._server_socket.accept()

        if len(self.clients) != self.max_client:
            client = Client(address, channel)
            # 소켓을 유용하고 편하게 사용하기 위해 Client 래퍼 객체로 생성
            try:
                self._sel.register(client.channel, selectors.EVENT_READ,
                                   client)  # selectors 이벤트 등록
                self.clients[client] = client
                # 클라이언트 리스트 등록

                EventManager.call_handler(CONNECT_CLIENT_EVENT, client=client)
            except socket.error as e:
                # todo: (try-except) 이제 이벤트 헨들러는 개별 스레드에서 처리하므로 try-except 필요가 없음
                with client:
                    if client != 2:
                        client.close()
        else:
            # 최대 클라이언트 연결 수를 넘어갔을 경우 꽉 찼다는 메시지르 보내고 연결 종료
            channel.sendall(make_message(FULL_CONN, self.host, address[0]))
            channel.close()
    def _monitor_clients(self):
        while self.is_running:
            time.sleep(self.wait_term)
            now = time.time()

            with self.lock_clients:
                for client in list(self.clients):
                    try:
                        with client:
                            if client.state == 2:
                                return

                            if client.last_receive_time is None or int(
                                    abs(now - client.last_receive_time)
                            ) > self.wait_term:
                                # 클라이언트의 마지막 수신 시각과 현재 시각을 비교해  heartbeat 전송 주기가 돌아오기 전까지 데이터가 수신한 적이 있는지 확인
                                if client.wait_count == self.max_wait_count:
                                    """
                                    클라이언트가 최대 heartbeat 허용 횟수를 넘긴 상태라면 연결이 끊긴 상태라고 판단하고 예외를 발생시켜 except 부분에서 클라이언트
                                    종료 처리
                                    """
                                    raise Exception
                                else:
                                    # 허용 횟수를 넘기지 않은 상태라면 heartbeat 메시지 전송 후 heartbeat 전송 횟수를 1 증가 시킴
                                    send_message(HEARTBEAT, self.host, client)
                                    client.wait_count += 1
                    except Exception as e:
                        with client:
                            if client.state != 2:
                                client.close()
                                EventManager.call_handler(
                                    DISCONNECTED_CLIENT_EVENT, client=client)
Exemplo n.º 4
0
    def __del__(self):
        dead = []
        for m in ResourceManager.mgrs:
            if not m():
                dead.append(m)
        for m in dead:
            ResourceManager.mgrs.remove(m)

        EventManager.__del__(self)
Exemplo n.º 5
0
    def __del__(self):        
        dead = []
        for m in ResourceManager.mgrs:
            if not m():
                dead.append(m)
        for m in dead:
            ResourceManager.mgrs.remove(m)

        EventManager.__del__(self)
Exemplo n.º 6
0
class ClipboardPipeline(object):
    def __init__(self):
        super().__init__()
        self.event_manager = EventManager()

    def process_item(self, item, spider):
        self.event_manager.update(item['url'], item)
        return item

    def close_spider(self, spider):
        ScraperData.add_data(self.event_manager.events.values())
Exemplo n.º 7
0
Arquivo: game.py Projeto: zrma/puyopy
    def __init__(self):
        """

        :rtype:
        """
        Timer.init()
        Renderer.init()
        self.__event = EventManager()
        self.__game_objects = {}
        self.__field = LogicField()

        self.__current_pu_yo: PuYo = None
Exemplo n.º 8
0
class Game(EventListener):
    keyboard: Keyboard = None
    event_manager: EventManager = None
    controller: Controller = None
    state: GameState = None

    def __init__(self) -> None:
        self.event_manager = EventManager()
        super(Game, self).__init__(self.event_manager)
        self.inialize_pygame()

        self.clock: pygame.Clock = Clock()
        self.screen: pygame.Surface = pygame.display.set_mode(
            constants.SCREEN_SIZE)

        self.keyboard = Keyboard(self.event_manager)

        self.state = GameState.LOAD_SCREEN
        self.controller = LaunchController(self.event_manager, self.screen)

    def notify(self, event: Event) -> None:
        if event == Event.QUIT:
            pygame.quit()
            sys.exit()
        elif event == Event.TICK:
            # limit the redraw speed to 30 frames per second
            self.clock.tick(30)
        elif event == Event.OPEN_SETTINGS:
            self.open_settings()
        elif event == Event.CLOSE_SETTINGS:
            self.close_settings()

    def run(self) -> None:
        while True:
            self.event_manager.post(Event.TICK)

    def inialize_pygame(self) -> None:
        pygame.mixer.pre_init(44100, -16, 4, 2048)
        pygame.init()
        pygame.font.init()

    def open_settings(self) -> None:
        if self.state == GameState.SETTINGS:
            return
        self.state = GameState.SETTINGS
        self.controller = SettingsController(self.event_manager, self.screen)

    def close_settings(self) -> None:
        if self.state == GameState.LOAD_SCREEN:
            return
        self.state = GameState.LOAD_SCREEN
        self.controller = LaunchController(self.event_manager, self.screen)
Exemplo n.º 9
0
    def __init__(self) -> None:
        self.event_manager = EventManager()
        super(Game, self).__init__(self.event_manager)
        self.inialize_pygame()

        self.clock: pygame.Clock = Clock()
        self.screen: pygame.Surface = pygame.display.set_mode(
            constants.SCREEN_SIZE)

        self.keyboard = Keyboard(self.event_manager)

        self.state = GameState.LOAD_SCREEN
        self.controller = LaunchController(self.event_manager, self.screen)
Exemplo n.º 10
0
 def insert_arrived_action(cmdline, action, devices, actionexec, pos=-1, **kwargs):
     if action is None:
         spl = shlex.split(cmdline)
         if len(spl) > 1:
             action = ActionAction.create_action(spl[1:], devices)
             randid = -1
             if action is not None:
                 randid = int(spl[0])
                 action.set_randomid(randid)
                 EventManager.fire(
                     eventname='ActionParsed', randid=randid, action=action)
                 actionexec.insert_action(action, pos)
     else:
         actionexec.insert_action(action, pos)
Exemplo n.º 11
0
    def __init__( self ):
        # Set the app to running
        self.running = True

        # Create the event manager
        self.events = EventManager( )
        self.events.registerListener( AppListener() )

        # Set the default app mode
        self.mode = 'menu'

        self.updateableObjects = {
            'game': [],
            'menu': []
        }
Exemplo n.º 12
0
    def __init__(self,
                 organization,
                 base_url,
                 start_date,
                 end_date,
                 date_format,
                 request_date_format=None):
        self.organization = organization
        # date_format is the string that specifies the date style of the target website
        if request_date_format == None:
            request_date_format = date_format

        self.date_format = date_format
        self.time_utils = TimeUtils(date_format)
        self.base_url = base_url
        self.identifier = re.sub(r'\W', '', base_url)
        self.event_manager = EventManager()

        request_format_utils = TimeUtils('%m-%d-%Y')
        # When this is running for multiple days, validating if the date is in the past causes issues
        self.start_date = request_format_utils.convert_date_format(
            start_date, request_date_format, validate_past=False)
        self.end_date = request_format_utils.convert_date_format(
            end_date, request_date_format, validate_past=False)
        self.start_timestamp = request_format_utils.min_timestamp_for_day(
            start_date)
        self.end_timestamp = request_format_utils.max_timestamp_for_day(
            end_date)
Exemplo n.º 13
0
class ClipboardPipeline(object):
    def __init__(self):
        super().__init__()
        self.event_manager = EventManager()

    def process_item(self, item, spider):
        self.event_manager.update(item['url'], item)
        return item

    def close_spider(self, spider):
        if len(self.event_manager.events) == 0:
            print('No data returned for ' + spider.base_url)
        spider.save_events([
            event.to_dict()
            for event in list(self.event_manager.events.values())
        ])
Exemplo n.º 14
0
    def __init__(self, name, label, width, height, show_fps, logging,
                 alignment, default_node_width, default_node_height, bg_color,
                 start_timers, structure_document, structure, hotkeys,
                 initializer, events):
        super(Window, self).__init__(name, label, width, height, show_fps,
                                     logging, alignment, default_node_width,
                                     default_node_height, bg_color,
                                     start_timers, structure_document,
                                     structure, hotkeys, initializer, events)

        glutInitWindowSize(self.width, self.height)

        # the window starts at the upper left corner of the screen
        # TODO: hook up alignment with this!
        glutInitWindowPosition(0, 0)

        self.window = glutCreateWindow(
            self.label)  # check if window ID is actually needed for something

        # glutFullScreen() # TODO: hook up this with conf!

        glutReshapeFunc(self.resize)
        glutVisibilityFunc(self.visibility)

        self.event_manager = EventManager(self.root_layout, self.hotkeys,
                                          self.events)

        setup_2D_projection(self.width, self.height)
Exemplo n.º 15
0
class Context(object):
    __metaclass__ = abc.ABCMeta
 
    state = 1 #class attribute to be used as the singleton's attribute
    eventManager=EventManager()
    camera=None
    state=None
    idle=stat.Idle()
    active=stat.Active()
    processor=process.InputProcessor()
    usersConteiner=cont.UsersConteiner()

    @abc.abstractmethod
    def __init__(self):
        pass #this prevents instantiation!
 
    @classmethod
    def printSelf(cls):
        print(cls.state) #prints out the value of the singleton's state
    @classmethod
    def otro(cls):
        cls.state+=1
    @classmethod
    def set_camera(cls, camera:camUtil.CameraInterface):
        cls.camera=camera
        cls.state=cls.idle
        cls.state.freeControl()
    
    @classmethod
    def stop(cls):
        cls.idle.suspend()
        cls.active.suspend()
Exemplo n.º 16
0
    def __init__(self, journalfile=None):
        self.eventManager = EventManager()
        self.journaller = Journaler(journalfile)
        self.sessions = {}

        # We load all sessions from the journal and add to our list
        for session in self.journaller.sessions():
            self.sessions[session.key] = session
Exemplo n.º 17
0
def run_server():
    bot = None
    cam = None
    try:
        try:
            app.bot_config = Config.read()
            bot = CoderBot.get_instance(
                servo=(app.bot_config.get("move_motor_mode") == "servo"),
                motor_trim_factor=float(
                    app.bot_config.get('move_motor_trim', 1.0)))
            audio = Audio.get_instance()
            audio.say(app.bot_config.get("sound_start"))
            try:
                cam = Camera.get_instance()
                Motion.get_instance()
            except picamera.exc.PiCameraError:
                logging.error("Camera not present")

            CNNManager.get_instance()
            EventManager.get_instance("coderbot")

            if app.bot_config.get('load_at_start') and app.bot_config.get(
                    'load_at_start'):
                app.prog = app.prog_engine.load(
                    app.bot_config.get('load_at_start'))
                app.prog.execute()
        except ValueError as e:
            app.bot_config = {}
            logging.error(e)

        bot.set_callback(PIN_PUSHBUTTON, button_pushed, 100)

        remove_doreset_file()

        app.run(host="0.0.0.0",
                port=5000,
                debug=True,
                use_reloader=False,
                threaded=True)
    finally:
        if cam:
            cam.exit()
        if bot:
            bot.exit()
        app.shutdown_requested = True
Exemplo n.º 18
0
    def close(self):
        """
        uninitial the koan lib.

        @rtype: None
        """
        koan.animManager.pooling()

        print '[Kernel.py] Before Fire Close'
        self.fire('Close')
        koan.animManager.pooling()

        if self._window:
            self._window.SetCore(None)
            self._window.Close()
            self._window = None

        EventManager.clear(self)
    def _receive_client_message(self, client: Client):
        try:
            with client:

                client.last_receive_time = time.time()
                client.wait_count = 0
                # 수신 한 경우 heartbeat 누적 수를 초기화
                # todo: Cleint receive 함수 내부에 처리할것

                header_bytes = client.receive(13)
                # 헤더 사이즈 만큼 버퍼에서 가져옴
                # todo: 사이즈가 작긴 하지만 이 부분도 아래 BODY 데이터를 가지고 오는 것처럼 처리를 해줘야함 (Client receive 함수 내에 처리)

                if not header_bytes:
                    if client.state != 2:
                        client.close()
                        EventManager.call_handler(DISCONNECTED_CLIENT_EVENT,
                                                  client=client)
                    # todo: 이벤트 호출자가 제어하지 않고, 함수 안에서 실행을 제어하도록 변경
                    #   예) 클라이언트 연결 이벤트에서 헨들러 A가 실행할때 어떠한 이유로 클라이언트를 종료시킨 경우 다음 번에 실행될
                    #   (이벤트에 대한 헨들러들이 순차적으로 실행됨) 클라이언트 연결 이벤트 헨들러 B가 실행 되면 안되므로
                    return

                header = Header.decode(header_bytes)

                if not header:
                    return

                body_bytes = client.receive(header.SIZE)
                # body 크기는 가변 적이므로 header에서 body 사이즈를 알아낸 후 버퍼에서 가져옴

                while len(body_bytes) < header.SIZE:
                    body_bytes += client.receive(header.SIZE - len(body_bytes))
                # 서버 상황상 명시한 사이즈 만큼 데이터를 가지고 온다는 보장이 없으므로, 완전할때까지 버퍼에서 가져옴

                receive_message(client, Message(header, body_bytes))

        except Exception as e:
            # 연결 혹은 받아온 데이터에 문제가 있으면 연결을 끊는거로 처리하고 있음
            with client:
                if client.state != 2:
                    client.close()
                    EventManager.call_handler(DISCONNECTED_CLIENT_EVENT,
                                              client=client)
Exemplo n.º 20
0
def main():
    ev_manager = EventManager()

    main_frame = MainFrame(ev_manager)
    spinner = CPUSpinnerController(ev_manager)
    keybd = KeyboardController(ev_manager)
    ai = Agent(ev_manager)
    app = App(ev_manager)

    spinner.run()
Exemplo n.º 21
0
    def __init__(self, parent):
        QtCore.QObject.__init__(self, parent)
        # Fix later
        self.__active = None
        self.__settings = None
        self.__panel_types = {}
        self.__panels = []
        self.__workspaces = list(self.Defaults)

        # TODO: a more official way to register panels.
        self.registerPanelType("JobWrangler", JobWranglerPanel)
        self.registerPanelType("Render Watch", RenderJobWatchPanel)
        self.registerPanelType("Tasks", TaskPanel)
        self.registerPanelType("Clusters", ClusterPanel)
        self.registerPanelType("Nodes", NodePanel)
        self.registerPanelType("Logs", LogsPanel)
        self.registerPanelType("Properties", PropertiesPanel)

        EventManager.bind("GLOBAL_REFRESH", self.refresh)
Exemplo n.º 22
0
    def __init__(self, parent):
        QtCore.QObject.__init__(self, parent)
        # Fix later
        self.__active = None
        self.__settings = None
        self.__panel_types = {}
        self.__panels = []
        self.__workspaces = list(self.Defaults)

        # TODO: a more official way to register panels.
        self.registerPanelType("JobWrangler", JobWranglerPanel)
        self.registerPanelType("Render Watch", RenderJobWatchPanel)
        self.registerPanelType("Tasks", TaskPanel)
        self.registerPanelType("Clusters", ClusterPanel)
        self.registerPanelType("Nodes", NodePanel)
        self.registerPanelType("Logs", LogsPanel)
        self.registerPanelType("Properties", PropertiesPanel)

        EventManager.bind("GLOBAL_REFRESH", self.refresh)
Exemplo n.º 23
0
    def close(self):
        """
        uninitial the koan lib.

        @rtype: None
        """
        koan.animManager.pooling()

        print '[Kernel.py] Before Fire Close'
        self.fire('Close')
        koan.animManager.pooling()


        if self._window:            
            self._window.SetCore(None)
            self._window.Close()
            self._window = None
        
        EventManager.clear(self)
Exemplo n.º 24
0
Arquivo: game.py Projeto: zrma/puyopy
class Game:
    def __init__(self):
        """

        :rtype:
        """
        Timer.init()
        Renderer.init()
        self.__event = EventManager()
        self.__game_objects = {}
        self.__field = LogicField()

        self.__current_pu_yo: PuYo = None

    def run(self):

        is_continue = True
        while is_continue:
            is_continue = self.__update()
            self.__render()

    def __update(self) -> bool:
        Timer.capture_time()

        current_event = self.__event.get_event()
        if isinstance(current_event, event.GameExitEvent):
            return False

        self.__field.update(current_event)
        self.__field.set_game_objects(tuple(self.__game_objects.values()))

        for game_object in self.__game_objects.values():
            assert isinstance(game_object, GameObject)
            game_object.update(current_event)

        current_pu_yo = self.__current_pu_yo
        if not current_pu_yo or not current_pu_yo.valid:
            new_pu_yo = PuYo(self.__field)
            self.__current_pu_yo = new_pu_yo
            self.__game_objects[new_pu_yo.id] = new_pu_yo

        return True

    def __render(self):
        if not Renderer.render_begin(self.__field.renderer):
            return

        for game_object in self.__game_objects.values():
            assert isinstance(game_object, GameObject)
            game_object.render()

        Renderer.render_end()
Exemplo n.º 25
0
def run_server():
    bot = None
    cam = None
    try:
        try:
            app.bot_config = Config.read()
            bot = CoderBot.get_instance(servo=(app.bot_config.get("move_motor_mode") == "servo"),
                                        motor_trim_factor=float(app.bot_config.get('move_motor_trim', 1.0)))
            audio = Audio.get_instance()
            audio.say(app.bot_config.get("sound_start"))
            try:
                cam = Camera.get_instance()
                Motion.get_instance()
            except picamera.exc.PiCameraError:
                logging.error("Camera not present")

            CNNManager.get_instance()
            EventManager.get_instance("coderbot")

            if app.bot_config.get('load_at_start') and app.bot_config.get('load_at_start'):
                app.prog = app.prog_engine.load(app.bot_config.get('load_at_start'))
                app.prog.execute()
        except ValueError as e:
            app.bot_config = {}
            logging.error(e)

        bot.set_callback(PIN_PUSHBUTTON, button_pushed, 100)

        remove_doreset_file()

        app.run(host="0.0.0.0", port=5000, debug=True, use_reloader=False, threaded=True)
    finally:
        if cam:
            cam.exit()
        if bot:
            bot.exit()
        app.shutdown_requested = True
Exemplo n.º 26
0
 def __init__(self, id, domain):
     """ Init method """
     self.id = id
     self.instancied = False
     self.event_name = "%s_on_set_value" % id
     self.e_mgr = EventManager()
     self.e_mgr.register_event(self.event_name)
     if len(domain) == 0:
         raise BTException()
     self.domain = domain
     
     if len(domain) == 1:
         self.set(domain[0])
     else:
         self.value = None
Exemplo n.º 27
0
def main():
    # Initialize pygame
    pygame.init()

    # Initialize event manager
    event_manager = EventManager()

    # Initialize display, input, and game data
    display_manager = Display(event_manager)
    input_manager = InputController(event_manager)
    game_model = GameModel(event_manager)
    clock = ClockController(event_manager)

    # Run game
    clock.run()
Exemplo n.º 28
0
 def __init__(self):
     """ Init method """
     self.constraints = []
     self.variables = {}
     self.public_solutions = []
     self.qstate = LifoQueue()
     self.phase = 'INIT'
     self.e_mgr = EventManager()
     self.e_mgr.register_event('solver_on_init')
     self.e_mgr.register_event('solver_on_end')
     self.e_mgr.register_event('solver_on_solution')
     self.e_mgr.register_event('solver_on_backtrack')
     self.e_mgr.register_event('solver_before_set_value')
     self.e_mgr.register_event('solver_after_set_value')
     self.e_mgr.raise_event('solver_on_init')
Exemplo n.º 29
0
    def __init__(self,
                 structure,
                 keys,
                 events=None,
                 constraints=None,
                 ui_initializer=None,
                 element_height=20):
        super(Application, self).__init__(structure, keys, events, constraints,
                                          ui_initializer, element_height)

        self.event_manager = EventManager(self.root_layout, keys, events)

        for event in ('mouse_x', 'mouse_y'):
            self.event_manager.key_events[BLENDER_KEYS[event]] = Event()
            self.event_manager.key_events[
                BLENDER_KEYS[event]].press = check_state_events

        self.window_manager = WindowManager()
        self.root_layout.common.window_manager = self.window_manager
        self.root_layout.common.invert_y = True

        global app
        app = self
Exemplo n.º 30
0
class TestEventManager(unittest.TestCase):
    """ Class for testing event.EventManager from cspy """

    def setUp(self):
        """ Prepare the test """
        self.e_mgr = EventManager()

    def test_singleton(self):
        """ Design pattern implemented correctly? """
        self.assertEqual(self.e_mgr._Singleton__instance, EventManager()._Singleton__instance)

    def test_subscription(self):
        """ Events are created correctly a recieved? """
        def function(**kwargs):
            """ Test function """
            self.assertEqual(1, kwargs['test'])
        self.e_mgr.register_event('test_event')
        self.e_mgr.subscribe('test_event', function)
        self.e_mgr.raise_event('test_event', test=1)
Exemplo n.º 31
0
sys.path.insert(0, '../google-calendar-api')
from main import getService, createEvent, deleteEvent, editEvent

# instantiate Slack client
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
# starterbot's user ID in Slack: value is assigned after the bot starts up
starterbot_id = None
#AUTH_TOKEN = "xoxp-405504331811-405638712146-405402172724-6911eeb1abd04a212f2e0ab6661889f5"
AUTH_TOKEN = "xoxb-405504331811-404929513808-vyzBLNNvgwh0TOqVyYggUxZl"

# constants
RTM_READ_DELAY = 1  # 1 second delay between reading from RTM
EXAMPLE_COMMAND = "do"
MENTION_REGEX = "^<@(|[WU].+?)>(.*)"

em = EventManager(slack_client, AUTH_TOKEN)

# google calendar
google_service = getService('token.json', 'credentials.json')


def parse_bot_commands(slack_events):
    """
        Parses a list of events coming from the Slack RTM API to find bot commands.
        If a bot command is found, this function returns a tuple of command and channel.
        If its not found, then this function returns None, None.
    """
    for event in slack_events:
        if event["type"] == "message" and not "subtype" in event:
            user_id, message = parse_direct_mention(event["text"])
            sender = event["user"]
Exemplo n.º 32
0
class SolverVariable():
    """ Varible class for cspy Solver. Each Variable has a domain. When a variable
    is set an unique event is raised.
    """

    def __init__(self, id, domain):
        """ Init method """
        self.id = id
        self.instancied = False
        self.event_name = "%s_on_set_value" % id
        self.e_mgr = EventManager()
        self.e_mgr.register_event(self.event_name)
        if len(domain) == 0:
            raise BTException()
        self.domain = domain
        
        if len(domain) == 1:
            self.set(domain[0])
        else:
            self.value = None

    def _restore(self, domain):
        """ Restore domain to a previous domain """
        self.domain = domain
        if len(domain) > 1:
            self.instancied = False
            self.value = None

    def set(self, val):
        """ Set the value to val and raise a event """
        self.domain = [val]
        self.value = val
        self.instancied = True
        self.e_mgr.raise_event(self.event_name, id=self.id, value=val)

    def remove_from_domain(self, values):
        """ Remove values from domain. If domain had more than one value
        and after remove only have one the variable become set.
        """
        # len before removing
        domain_len = len(self.domain)
        for value in values:
            if self.in_domain(value):
                self.domain.remove(value)
        # No values is an invalid states
        if len(self.domain) == 0:
            raise BTException()
        # Now the variable is set
        elif len(self.domain) == 1 and domain_len > 1:
            self.set(self.domain[0])

    def subscribe(self, function):
        """ Subscribe to variable event """
        self.e_mgr.subscribe(self.event_name, function)

    def in_domain(self, value):
        """ Is the value in the domain?  """
        return value in self.domain

    def min(self):
        """ Min posible value of the variable"""
        return min(self.domain)

    def max(self):
        """ Max posible value of the variable"""
        return max(self.domain)

    def __str__(self):
        """ String representation of the variable """
        return str(self.domain)
Exemplo n.º 33
0
class App( ):

    # -------- Init --------
    # Constructor, creates the app and sets it to running.
    #
    # @return App
    def __init__( self ):
        # Set the app to running
        self.running = True

        # Create the event manager
        self.events = EventManager( )
        self.events.registerListener( AppListener() )

        # Set the default app mode
        self.mode = 'menu'

        self.updateableObjects = {
            'game': [],
            'menu': []
        }

        self.colliders = []

    # -------- Tick --------
    # Process a single tick of the game loop.
    #
    # @param  int  frameTime Number of milliseconds passed since the previous tick.
    # @param  int  lifeTime  Number of milliseconds since pygame initialised.
    # @return None
    def tick( self, frameTime, lifeTime ):
        if 'game' == self.mode:
            self.tickGame( frameTime, lifeTime )
        else:
            self.tickMenu( frameTime, lifeTime )

    # -------- Tick Game --------
    # Process a single tick within the game mode.
    #
    # @param  int  frameTime Number of milliseconds passed since the previous tick.
    # @param  int  lifeTime  Number of milliseconds since pygame initialised.
    # @return None
    def tickGame( self, frameTime, lifeTime ):

        # Fill with black
        config.screen.fill( config.settings['screen_fill'] )

        # Update sprites
        print len(self.updateableObjects['game'])
        for obj in self.updateableObjects['game']:
            obj.update( int(frameTime), int(lifeTime) )

        # Run checks on colliders
        for collider in self.colliders:
            collider.check( )

        # Draw sprites
        rects = config.sprites.draw( config.screen )

        #pygame.display.update( rects )

        pygame.display.flip( )

    # -------- Tick Menu --------
    # Process a single tick within the menu mode.
    #
    # @param  int  frameTime Number of milliseconds passed since the previous tick.
    # @param  int  lifeTime  Number of milliseconds since pygame initialised.
    # @return None
    def tickMenu( self, frameTime, lifeTime ):
        for obj in self.updateableObjects['menu']:
            pass


    def addUpdateableObject( self, mode, obj ):
        if obj not in self.updateableObjects[mode]:
            self.updateableObjects[mode].append( obj )

    def removeUpdateableObject( self, mode, obj ):
        if obj in self.updateableObjects[mode]:
            self.updateableObjects[mode].remove( obj )

    def addCollider( self, collider ):
        self.colliders.append( collider )

    def setMode( self, mode ):
        self.mode = mode

    def setWorld( self, world ):
        self.world = world
Exemplo n.º 34
0
def main():
    board = Board(6, 5)
    board.init()
    board.fill_random()

    evtmgr = EventManager()
    cpu = CPUTickController(evtmgr)
    evtmgr.add(cpu)
    evtmgr.add(KeyboardController(evtmgr))
    evtmgr.add(PygameController(evtmgr))
    evtmgr.add(ModelController(evtmgr, board))
    evtmgr.add(AnimationController(evtmgr, board))
    evtmgr.trigger(InitEvent())
    cpu.run()
Exemplo n.º 35
0
 def __init__(self):
     EventManager.__init__(self)
     self._window = None
     self.ending = False
     self.preIdleTime = time.time()
Exemplo n.º 36
0
class Solver(object):
    """ Solve CSP problems getting all solutions """
    PHASES = ['INIT', 'SOLVING', 'FINISHED']
    def __init__(self):
        """ Init method """
        self.constraints = []
        self.variables = {}
        self.public_solutions = []
        self.qstate = LifoQueue()
        self.phase = 'INIT'
        self.e_mgr = EventManager()
        self.e_mgr.register_event('solver_on_init')
        self.e_mgr.register_event('solver_on_end')
        self.e_mgr.register_event('solver_on_solution')
        self.e_mgr.register_event('solver_on_backtrack')
        self.e_mgr.register_event('solver_before_set_value')
        self.e_mgr.register_event('solver_after_set_value')
        self.e_mgr.raise_event('solver_on_init')

    def _push_state(self, variable, value):
        """ Store in qstate the value of the variable it going to be set next
        and the state of the all domains
        """
        domain_dump = {}
        for var in self.variables.itervalues():
            # store a copy of the domain
            domain_dump[var.id] = var.domain[:]
        self.qstate.put((variable.id, value, domain_dump))

    def _pop_state(self):
        """ Restore previous state """
        return self.qstate.get(False)
    
    def _back_to_previous_state(self):
        """ Go back to a previous valid state removing invalid values.
        If qstate become empty (there is no valid state) return false 
        else true.
        """
        while not self.qstate.empty():
            state = self._pop_state()
            id_var = state[0]
            value = state[1]
            domain_dump = state[2]
            # Restore domains
            for id, domain in domain_dump.iteritems():
                self.variables[id]._restore(domain)
            # Delete invalid value
            try:
                self.variables[id_var].remove_from_domain([value])
                return True
            except:
                pass
        return False

    def reg_variable(self, variable):
        """ Register a variable to the problem. """
        self.variables[variable.id] = variable

    def _public_solution(self):
        """ Store in public_solutions a id_variable -> value hash """
        solution = {}
        for id_var, variable in self.variables.iteritems():
            solution[id_var] = variable.value
        self.public_solutions.append(solution)
        return solution

    def next_variable(self):
        """ Choose what variable is the best to be instancied. """
        for variable in self.variables.values():
            if not variable.instancied:
                return variable

    def value(self, variable):
        """ Choose the better value to the variable. """
        return variable.min()

    def solve(self):
        """ Get all solutions to the problem. """
        while self.iter_solve():
            pass
        return self.public_solutions

    def iter_solve(self):
        """ Get all the solutions one by one using a backtracking strategy."""
        if self.phase == 'INIT':
            self.phase = 'SOLVING'
        elif not self._back_to_previous_state():
            # No more solutions
            self.e_mgr.raise_event('solver_on_end')
            self.phase = 'FINISHED'
            return None
        while not self.all_instancied():
            try:
                # Heuristic
                var = self.next_variable()
                value = self.value(var)
                self.e_mgr.raise_event('solver_before_set_value')
                self._push_state(var, value)
                var.set(value)
                self.e_mgr.raise_event('solver_after_set_value')
            except BTException, bte:
                if not self._back_to_previous_state():
                    # No more solutions
                    self.phase = 'FINISHED'
                    self.e_mgr.raise_event('solver_on_end')
                    return None
                else:
                    self.e_mgr.raise_event('solver_on_backtrack')
        # Solution
        solution = self._public_solution()
        self.e_mgr.raise_event('solver_on_solution')
        return solution
Exemplo n.º 37
0
class Simulator(object):

    def __init__(self, network_file_path, configs):
        self.configs = configs
        self.file_path = network_file_path

        # Initialize the event manager
        self.mgr = EventManager()
        self.collector = DataCollector()

        # Read network in from file.
        with open(file_path, 'r') as yaml_file:
            network = yaml.load(yaml_file)

        # Initialize the network components
        self.hosts = {}
        for host_name in network['hosts']:
            self.hosts[host_name] = Host(host_name, self, self.collector)

        self.routers = {}
        if 'routers' in network:
            for router_name in network['routers']:
                self.routers[router_name] = Router(router_name, self)

        self.flows = {}
        for flow_dict in network['flows']:
            flow_name = flow_dict.keys()[0]
            flow_desc = flow_dict[flow_name]

            self.flows[flow_name] = Flow(
                flow_name,
                self,
                self.collector,
                self.hosts[flow_desc['source']] ,
                self.hosts[flow_desc['destination']],
                flow_desc['amount'],
                flow_desc['start']
            )

        self.links = {}
        host_prefixes = ['H', 'S', 'T']
        for link_dict in network['links']:
            link_name = link_dict.keys()[0]
            link_desc = link_dict[link_name]

            aname = link_desc['anode']
            bname = link_desc['bnode']

            ahost = self.hosts[aname] \
                if aname[0] in host_prefixes else self.routers[aname]
            bhost = self.hosts[bname] \
                if bname[0] in host_prefixes else self.routers[bname]

            link = Link(
                link_name,
                self,
                self.collector,
                link_desc['rate'] / 8.0,
                link_desc['delay'],
                link_desc['buffer'],
                link_desc['buffer'],
                ahost,
                bhost
            )

            self.links[link_name] = link

            ahost.set_link(link)
            bhost.set_link(link)

            self.mgr.add_event(0.0, link.calculate_throughput, [])

        # Add initial events for each of the flows
        for flow in self.flows.values():
            self.mgr.add_event(flow.start_t, flow.send_packet, [])

            if not configs['tcpreno']:
                self.mgr.add_event(flow.start_t, flow.tcp_fast_update, [])

        # Initialize the routing tables
        for router in self.routers.values():
            router.init_routing_table()

        if len(self.routers) > 0:
            self.mgr.add_event(0.0, self.routers['R1'].send_rout_packet, [])
            self.mgr.add_event(self.mgr.t + configs['dynamic_routing_step'],
                               self.start_dynamic_routing, [])

    def get_data(self):
        """Telling all of the objects to report their data."""

        for flow in self.flows.values():
            self.mgr.add_event(0.0, flow.report_rates, [0.1, 0, 0])
            self.mgr.add_event(0.0, flow.report_link_rates, [0.2, {}])

        for link in self.links.values():
            self.mgr.add_event(0.0, link.report_occupancy, [0.1])
            self.mgr.add_event(0.0, link.report_dropped, [0.1])
            self.mgr.add_event(0.0, link.report_throughput, [0.5])

        for host in self.hosts.values():
            self.mgr.add_event(0.0, host.report_rates, [0.1, 0, 0])

    def start_dynamic_routing(self):
        # Initialize the routing tables and send out routing packets
        for router in self.routers.values():
            router.init_routing_table(temp_table=True)
            router.start_dynamic_routing()
            router.send_rout_packet(True)

        self.mgr.add_event(self.mgr.t + self.configs['dynamic_routing_step'],
                           self.start_dynamic_routing, [])

    def check_done_dynamic_routing(self):
        time_step = 0.01
        num_not_done = 0

        for router in self.routers.values():
            if not router.done_d_routing:
                num_not_done += 1

        if num_not_done == 0:
            for router in self.routers.values():
                router.finish_dynamic_routing()

            for link in self.links.values():
                link.time_through_link_update()

    def run(self):

        # Starting data collection
        self.get_data()

        while self.mgr.has_events():
            (t, event, args) = self.mgr.pop_event()
            self.mgr.t = t
            event(*args)

            # Check if all our flows have terminated
            flows_not_done = len(self.flows)
            for flow in self.flows.values():
                if flow.last_acknowledged == flow.max_seq:
                    flows_not_done -= 1

            if flows_not_done == 0:
                break

        print 'Done with all events at time: {}'.format(self.mgr.t)

    def plot(self):
        # Get only the file_name
        file_name = self.file_path.split("/")[-1].rstrip(".yml")

        # Print the plots to pdf
        plot_dir = "plots/"

        # Whether or not its reno or fast
        if self.configs['tcpreno']:
            mode = '_reno'
        else:
            mode = '_fast'

        # Pdf page
        pp = PdfPages(plot_dir + file_name + mode + '.pdf')

        print 'Plotting to {}'.format(plot_dir + file_name + mode + '.pdf')

        collecs = self.collector.collection.keys()
        collecs.sort()

        for g in collecs:
            self.collector.graph_data(pp, g, g)

        if file_name =='testcase0':
            # The congestion window for the flow
            self.collector.graph_data(pp, 'F1 Congestion Window', 'F1_cwnd')

        elif file_name == 'testcase1':
            # The congestion window for the flow
            self.collector.graph_data(pp, 'F1 Congestion Window', 'F1_cwnd')

            # The link rates of L1 and L2
            self.collector.combine_graphs(
                pp, 'Test Case 1 Link Rates',
                ['F1_L1_rate', 'F1_L2_rate'],
                labels=['L1', 'L2']
            )

            # The link rates of L3 and L4
            self.collector.combine_graphs(
                pp,
                'Test Case 1 Link Rates',
                ['F1_L3_rate', 'F1_L4_rate'],
                labels=['L3', 'L4']
            )

        elif file_name == 'testcase2':
            self.collector.combine_graphs(
                pp,
                'Test Case 2 Flow Congestion Windows',
                ['F1_cwnd', 'F2_cwnd', 'F3_cwnd'],
                labels=['F1', 'F2', 'F3']
            )

            self.collector.combine_graphs(
                pp,
                'Test Case 2 Buffer Occupancy',
                ['L1_a_occupancy', 'L2_a_occupancy', 'L3_a_occupancy'],
                labels=['L1a', 'L2a', 'L3a']
            )

        pp.close()
Exemplo n.º 38
0
 def close(self):
     self.clearAll()
     EventManager.close(self)
     self.window = koan.Null
Exemplo n.º 39
0
 def __init__(self):
     super().__init__()
     self.event_manager = EventManager()
Exemplo n.º 40
0
 def __init__(self, *argv, **argd):
     list.__init__(self, *argv, **argd)
     EventManager.__init__(self)
    def __init__(self):
        super().__init__()
        self.file_fetch_dict = FileFetchDict()

        EventManager.register_handler(DISCONNECTED_CLIENT_EVENT,
                                      self._check_disconnect_client)
Exemplo n.º 42
0
 def __init__(self):
     EventManager.__init__(self)
     self._window = None
     self.ending = False
     self.preIdleTime = time.time()
Exemplo n.º 43
0
class App( ):

    # -------- Init --------
    # Constructor, creates the app and sets it to running.
    #
    # @return App
    def __init__( self ):
        # Set the app to running
        self.running = True

        # Create the event manager
        self.events = EventManager( )
        self.events.registerListener( AppListener() )

        # Set the default app mode
        self.mode = 'menu'

        self.updateableObjects = {
            'game': [],
            'menu': []
        }

    # -------- Tick --------
    # Process a single tick of the game loop.
    #
    # @param  int  frameTime Number of milliseconds passed since the previous tick.
    # @param  int  lifeTime  Number of milliseconds since pygame initialised.
    # @return None
    def tick( self, frameTime, lifeTime ):
        if 'game' == self.mode:
            self.tickGame( frameTime, lifeTime )
        else:
            self.tickMenu( frameTime, lifeTime )

    # -------- Tick Game --------
    # Process a single tick within the game mode.
    #
    # @param  int  frameTime Number of milliseconds passed since the previous tick.
    # @param  int  lifeTime  Number of milliseconds since pygame initialised.
    # @return None
    def tickGame( self, frameTime, lifeTime ):

        # Fill with black
        config.screen.fill( config.settings['screen_fill'] )

        # Update sprites
        for obj in self.updateableObjects['game']:
            obj.update( int(frameTime), int(lifeTime) )

        # Draw sprites
        rects = config.sprites.draw( config.screen )

        #pygame.display.update( rects )

        pygame.display.flip( )

    # -------- Tick Menu --------
    # Process a single tick within the menu mode.
    #
    # @param  int  frameTime Number of milliseconds passed since the previous tick.
    # @param  int  lifeTime  Number of milliseconds since pygame initialised.
    # @return None
    def tickMenu( self, frameTime, lifeTime ):
        for obj in self.updateableObjects['menu']:
            pass


    def addUpdateableObject( self, mode, obj ):
        self.updateableObjects[mode].append( obj )

    def setMode( self, mode ):
        self.mode = mode

    def setWorld( self, world ):
        self.world = world
Exemplo n.º 44
0
def main(argv=None):  # IGNORE:C0111
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (
        program_version, program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by user_name on %s.
  Copyright 2016 organization_name. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ap.ArgumentParser(
            description=program_license, formatter_class=ap.RawDescriptionHelpFormatter)
        parser.add_argument("-c", "--conf", dest="conf", action=ActionConf)
        parser.add_argument("-b", "--broadcast", dest="broadcast")
        parser.add_argument("-m", "--mqtt-host",
                            dest="mqtt_host", type=valid_host)
        parser.add_argument("-k", "--mqtt-port",
                            dest="mqtt_port", type=valid_port)
        parser.add_argument("-f", "--prime-host",
                            dest="prime_host", type=valid_host)
        parser.add_argument("-y", "--prime-port",
                            dest="prime_port", type=valid_port)
        parser.add_argument("-w", "--prime-port2",
                            dest="prime_port2", type=valid_port)
        parser.add_argument("-q", "--prime-code",
                            dest="prime_code", type=valid_code)
        parser.add_argument("-z", "--prime-pass", dest="prime_pass")
        parser.add_argument("-p", "--port", dest="port", type=valid_port)
        parser.add_argument("-s", "--tcpport", dest="tcpport", type=valid_port)
        parser.add_argument("-g", "--httpport",
                            dest="httpport", type=valid_port)
        parser.add_argument("-t", "--timeout",
                            dest="timeout", type=valid_timeout)
        parser.add_argument("-j", "--emitdelay",
                            dest="emit_delay", type=valid_delay)
        parser.add_argument("-r", "--retry", dest="retry", type=valid_retry)
        parser.add_argument("-a", "--action", dest="actions",
                            nargs='+', action=ActionAction)
        parser.add_argument('-x', '--active_on_finish',
                            action='store_true', dest="active_on_finish")
        parser.add_argument('-V', '--version', action='version',
                            version=program_version_message)
        parser.add_argument('-d', '--debug', action='store_true', dest="debug")
        parser.add_argument(
            '-e', '--remote', action='store_true', dest="remote")

        parser.set_defaults(conf=os.path.join(os.getcwd(), 'devices.xml'),
                            devices={},
                            mqtt_host='',
                            mqtt_port=1883,
                            emit_delay=0,
                            port=10000,
                            tcpport=2802,
                            httpport=2803,
                            actions=[],
                            broadcast='255.255.255.255',
                            active_on_finish=False,
                            timeout=1,
                            retry=3,
                            debug=False,
                            remote=False,
                            prime_host='',
                            prime_port=80,
                            prime_port2=6004,
                            prime_code='',
                            prime_pass=''
                            )

        def connect_devices(devices):
            for _, dv in devices.copy().items():
                dv.connect_devices(devices)

        def add_discovered_devices(action, devices, mqtt_client, mqtt_userdata, emit_delay, **kwargs):
            for _, v in action.hosts.copy().items():
                # _LOGGER.info("current "+k+" nm "+v.name+" lndv "+str(len(devices)))
                already_saved_device = None
                # _LOGGER.info("Confronto "+v.name)
                for _, dv in devices.copy().items():
                    # _LOGGER.info("VS "+v.name+'/'+dv.name)
                    if v.mac == dv.mac:
                        already_saved_device = dv
                        break
                    # elif v.name==dv.name:
                    #    _LOGGER.info("Are you sure? "+v.name+"->"+v.mac.encode('hex')+"/"+dv.mac.encode('hex'))
                if already_saved_device is None:
                    # _LOGGER.info("changed "+str(v))
                    devices.update({v.name: v})
                    action.m_device = True
                else:
                    already_saved_device.on_stop()
                    v.copy_extra_from(already_saved_device)
                    v.name = already_saved_device.name
                    if isinstance(v, IrManager):
                        v.set_emit_delay(emit_delay)
                    devices.update({already_saved_device.name: v})
                if mqtt_client and mqtt_client.is_connected():
                    v.mqtt_start(mqtt_client, mqtt_userdata)
            connect_devices(devices)

        def save_modified_devices(save_filename, save_devices, debug, device, action, **kwargs):
            # _LOGGER.info("lensv "+str(len(save_devices)))
            save = True
            if isinstance(action, ActionDiscovery):
                save = debug or action.modifies_device()
            elif isinstance(action, ActionViewtable):
                save = False
                if isinstance(action, ActionViewtable1):
                    save = debug
                elif isinstance(action, ActionViewtable4):
                    dn = device.default_name()
                    if dn in save_devices and dn != device.name:
                        del save_devices[dn]
                        save_devices[device.name] = device
                        save = True
                    else:
                        save = debug
                elif isinstance(device, DeviceS20):
                    save = debug
                elif isinstance(device, IrManager):
                    save = debug or action.modifies_device()
            elif isinstance(action, ActionStatechange) or isinstance(action, ActionSubscribe):
                save = debug
            if save:
                Device.save(save_devices, save_filename,
                            (DEVICE_SAVE_FLAG_MAIN | DEVICE_SAVE_FLAG_TABLE) if debug else DEVICE_SAVE_FLAG_MAIN)

        def terminate_on_finish(actionexec, force=False, **kwargs):
            if force or actionexec.action_list_len() <= 1:
                _LOGGER.info("Terminating...")
                global term_called
                term_called = True

        def do_timer_action(device, timerobj, actionexec, **kwargs):
            act = ActionEmitir(device, *tuple(timerobj['action'].split(' ')))
            actionexec.insert_action(act)

        def insert_arrived_action(cmdline, action, devices, actionexec, pos=-1, **kwargs):
            if action is None:
                spl = shlex.split(cmdline)
                if len(spl) > 1:
                    action = ActionAction.create_action(spl[1:], devices)
                    randid = -1
                    if action is not None:
                        randid = int(spl[0])
                        action.set_randomid(randid)
                        EventManager.fire(
                            eventname='ActionParsed', randid=randid, action=action)
                        actionexec.insert_action(action, pos)
            else:
                actionexec.insert_action(action, pos)

        def handle_device_dl(action, devices, **kwargs):
            if action is not None:
                action.set_devices(devices)

        def process_state_change(hp, newstate, devices, mac, actionexec, **kwargs):
            _LOGGER.info(f'ExtStateChange {mac}')
            for _, dv in devices.items():
                if mac == dv.mac:
                    act = ActionNotifystate(dv, newstate)
                    actionexec.insert_action(act, 1)

        def mqtt_subscribe(client, userdata, who, lsttopics):
            if userdata and userdata.mqtt_mid is not None:
                if isinstance(who, str):
                    log = key = who
                else:
                    key = str(id(who))
                    log = who.name
                _, mid = client.subscribe(lsttopics)
                userdata.mqtt_mid[key] = mid
                _LOGGER.info(f"Asked for subscription for {log} with mid {mid}")

        def mqtt_on_connect(client, userdata, flags, rc):
            if userdata.mqtt_mid is None and not rc:
                _LOGGER.info("__main__ connect")
                userdata.mqtt_mid = dict()
                mqtt_subscribe(client, userdata, "__main__", [("cmnd/#", 0,)])
                for _, d in userdata.devices.items():
                    d.mqtt_start(client, userdata)
            else:
                _LOGGER.info(f"Ignoring connack rc {rc}")

        def mqtt_on_subscribe(client, userdata, mid, granted_qos):
            if userdata and userdata.mqtt_mid is not None:
                log = 'N/A'
                if "__main__" in userdata.mqtt_mid and userdata.mqtt_mid["__main__"] == mid:
                    userdata.mqtt_mid["__main__"] = -1
                    log = "__main__"
                else:
                    for _, d in userdata.devices.items():
                        key = str(id(d))
                        if key in userdata.mqtt_mid and userdata.mqtt_mid[key] == mid:
                            userdata.mqtt_mid[key] = -1
                            log = d.name
                            d.mqtt_on_subscribe(client, userdata, mid, granted_qos)
                            break
                _LOGGER.info(f"{log} subscribed: mid={mid} qos={granted_qos}")

        def mqtt_on_message(client, userdata, msg):
            topic = msg.topic
            _LOGGER.info(f"Received {b2s(msg.topic)}, pay {b2s(msg.payload)}")
            i = topic.rfind("/")
            if i >= 0 and i < len(topic) - 1:
                sub = topic[i + 1:]
                if sub == "devicedl":
                    resp = json.dumps(userdata.devices)
                    client.publish("stat/devicedl", resp)
                else:
                    for _, d in userdata.devices.items():
                        d.mqtt_on_message(client, userdata, msg)

        def mqtt_on_publish(client, userdata, mid):
            _LOGGER.info("Someone pub mid: " + str(mid))

        def mqtt_on_disconnect(client, userdata, rc):
            _LOGGER.info("disconnect with rc: " + str(rc))
            userdata.mqtt_mid = None

        def mqtt_init(hp, ud):
            ud.mqtt_mid = None
            ud.mqtt_subscribe = mqtt_subscribe
            client = paho.Client(userdata=ud, protocol=paho.MQTTv31)
            client.on_connect = mqtt_on_connect
            client.on_message = mqtt_on_message
            client.on_subscribe = mqtt_on_subscribe
            client.on_disconnect = mqtt_on_disconnect
            client.on_publish = mqtt_on_publish
            _LOGGER.info("mqtt_start (%s:%d)" % hp)
            client.connect_async(hp[0], port=hp[1])
            client.loop_start()
            return client

        def mqtt_stop(client):
            client.on_disconnect = None
            client.loop_stop()
            client.disconnect()

        # Process arguments
        signal(SIGTERM, sigterm_handler)
        _LOGGER.info("Parsing args")
        args = parser.parse_args()
        mqtt_client = None
        if len(args.mqtt_host):
            mqtt_client = mqtt_init((args.mqtt_host, args.mqtt_port), args)

        _LOGGER.info(str(args))
        _LOGGER.info(args.devices)
        connect_devices(args.devices)
        actionexec = ActionExecutor()
        if not args.active_on_finish:
            EventManager.on('ActionDone', terminate_on_finish,
                            actionexec=actionexec)
        pars = {'save_filename': args.conf,
                'save_devices': args.devices, 'debug': args.debug}
        EventManager.on('TimerAction', do_timer_action,
                        actionexec=actionexec, **pars)
        EventManager.on('ActionDiscovery', add_discovered_devices, devices=args.devices,
                        mqtt_client=mqtt_client, mqtt_userdata=args, emit_delay=args.emit_delay)
        EventManager.on('ExtInsertAction', insert_arrived_action,
                        devices=args.devices, actionexec=actionexec)
        EventManager.on('ExtChangeState', process_state_change,
                        actionexec=actionexec, devices=args.devices)
        EventManager.on('ActionDiscovery', save_modified_devices, **pars)
        EventManager.on('ActionLearnir', save_modified_devices, **pars)
        EventManager.on('ActionEditraw', save_modified_devices, **pars)
        EventManager.on('ActionSubscribe', save_modified_devices, **pars)
        EventManager.on('ActionViewtable1', save_modified_devices, **pars)
        EventManager.on('ActionInsertKey', save_modified_devices, **pars)
        EventManager.on('ActionViewtable3', save_modified_devices, **pars)
        EventManager.on('ActionViewtable4', save_modified_devices, **pars)
        EventManager.on('ActionStatechange', save_modified_devices, **pars)
        EventManager.on('ActionStateon', save_modified_devices, **pars)
        EventManager.on('ActionStateoff', save_modified_devices, **pars)
        EventManager.on('ActionCreatesh', save_modified_devices, **pars)
        EventManager.on('ActionDevicedl', handle_device_dl,
                        devices=args.devices, **pars)
        EventManager.on('ActionExit', terminate_on_finish,
                        actionexec=actionexec, force=True)
        actionexec.configure(args)
        if len(args.mqtt_host):
            actionexec.insert_action(ActionPause("5"))
            actionexec.insert_action(ActionDiscovery())
        actionexec.insert_action(args.actions)

        stopped = False
        numv = 2
        while threading.active_count() > 1 and numv > 1:
            try:
                time.sleep(1)
                if stopped:
                    thl = threading.enumerate()
                    rv = ""
                    numv = 0
                    for th in thl:
                        if not th.daemon:
                            numv += 1
                        rv += th.name + " "
                    _LOGGER.info("TH=%s" % rv)
                elif term_called:
                    raise KeyboardInterrupt
            except KeyboardInterrupt:
                if not stopped:
                    _LOGGER.info("Stopping")
                    stopped = True
                    actionexec.stop()
                    if mqtt_client:
                        mqtt_stop(mqtt_client)
                    for _, k in args.devices.copy().items():
                        k.on_stop()
        return 0
    except KeyboardInterrupt:
        # handle keyboard interrupt ###
        return 0
    except Exception as e:
        if DEBUG or TESTRUN:
            raise(e)
        _LOGGER.warning(f"{traceback.format_exc()}")
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2
Exemplo n.º 45
0
    def __init__(self, network_file_path, configs):
        self.configs = configs
        self.file_path = network_file_path

        # Initialize the event manager
        self.mgr = EventManager()
        self.collector = DataCollector()

        # Read network in from file.
        with open(file_path, 'r') as yaml_file:
            network = yaml.load(yaml_file)

        # Initialize the network components
        self.hosts = {}
        for host_name in network['hosts']:
            self.hosts[host_name] = Host(host_name, self, self.collector)

        self.routers = {}
        if 'routers' in network:
            for router_name in network['routers']:
                self.routers[router_name] = Router(router_name, self)

        self.flows = {}
        for flow_dict in network['flows']:
            flow_name = flow_dict.keys()[0]
            flow_desc = flow_dict[flow_name]

            self.flows[flow_name] = Flow(
                flow_name,
                self,
                self.collector,
                self.hosts[flow_desc['source']] ,
                self.hosts[flow_desc['destination']],
                flow_desc['amount'],
                flow_desc['start']
            )

        self.links = {}
        host_prefixes = ['H', 'S', 'T']
        for link_dict in network['links']:
            link_name = link_dict.keys()[0]
            link_desc = link_dict[link_name]

            aname = link_desc['anode']
            bname = link_desc['bnode']

            ahost = self.hosts[aname] \
                if aname[0] in host_prefixes else self.routers[aname]
            bhost = self.hosts[bname] \
                if bname[0] in host_prefixes else self.routers[bname]

            link = Link(
                link_name,
                self,
                self.collector,
                link_desc['rate'] / 8.0,
                link_desc['delay'],
                link_desc['buffer'],
                link_desc['buffer'],
                ahost,
                bhost
            )

            self.links[link_name] = link

            ahost.set_link(link)
            bhost.set_link(link)

            self.mgr.add_event(0.0, link.calculate_throughput, [])

        # Add initial events for each of the flows
        for flow in self.flows.values():
            self.mgr.add_event(flow.start_t, flow.send_packet, [])

            if not configs['tcpreno']:
                self.mgr.add_event(flow.start_t, flow.tcp_fast_update, [])

        # Initialize the routing tables
        for router in self.routers.values():
            router.init_routing_table()

        if len(self.routers) > 0:
            self.mgr.add_event(0.0, self.routers['R1'].send_rout_packet, [])
            self.mgr.add_event(self.mgr.t + configs['dynamic_routing_step'],
                               self.start_dynamic_routing, [])
Exemplo n.º 46
0
 def setUp(self):
     """ Prepare the test """
     self.e_mgr = EventManager()