Exemplo n.º 1
0
    def __init__(self):
        """Initialize game variables"""
        self.clock = pygame.time.Clock()
        self.current_map_name = "world"
        self.maps = {
            "world":Map('Maps/map0.txt', 'images/ProjectUtumno_full.png', screen_size),
            "shop": Map('Maps/map_shop.txt', 'images/ProjectUtumno_full.png', screen_size),
            "dungeon":Map('Maps/map_dungeon.txt', 'images/ProjectUtumno_full.png', screen_size),
        }

        self.current_map = self.maps[self.current_map_name]

        self.running = False
        self.window = pygame.display.set_mode(screen_size)
        self.player = Player('images/star.png')

        self.bg_color = (0,0,0)
        self.event_manager = EventManager()
        self.event_manager.addGameObject(self.player)
        self.camera = Camera(self.current_map)
        self.event_manager.addGameObject(self.camera)

        # feel free to move this to its own method or wherever, just using for testing
        for enemy in self.current_map.enemy_list.sprites():
            self.event_manager.addGameObject(enemy)

        self.warpCoordinates = {
            "world": [(self.player.position.x,self.player.position.y)],
            "shop": [(320,590),(1360,334)],
            "dungeon": [(2816,1600),(1440,1525)]
        }
Exemplo n.º 2
0
    def __init__(self, maxfps=40):
        self.evManager = EventManager()
        self.evManager.RegisterListener(self)

        self.keepGoing = 1
        self.clock = pygame.time.Clock()
        self.maxfps = maxfps
Exemplo n.º 3
0
    def __init__(self):
        self.eventManager = EventManager()
        self.running = True

        self.uid = 0

        self.game = None
        self.state = PlayerState.chooseName
        self.inputManager = InputManager()
        self.gameState = None

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.serverHost = Server.host
        self.serverPort = Server.port
        self.clientHost = "192.168.0.106"
        self.clientPort = 5002
        self.sock.bind((self.clientHost, self.clientPort))

        self.lock = threading.Lock()
        self.packets = Queue()
        self.networkingThread = threading.Thread(target=self.networking)
        self.networkingThread.daemon = True
        self.networkingThread.start()

        self.sendAlive = Server.checkAlive - 1 / 2
        self.nextAlive = 0

        print "Client started"
Exemplo n.º 4
0
class CPUSpinnerController(object):
    """Controls the game clock -- generating an Event for each game tick, and throttling
		the game to limit CPU usage"""
    def __init__(self, maxfps=40):
        self.evManager = EventManager()
        self.evManager.RegisterListener(self)

        self.keepGoing = 1
        self.clock = pygame.time.Clock()
        self.maxfps = maxfps

    def Run(self):
        """Start the game by telling the game clock to go!"""
        while self.keepGoing:
            event = TickEvent(pygame.time.get_ticks(),
                              self.clock.tick(self.maxfps))
            self.evManager.Notify(event)

    def Notify(self, event):
        """handled events:
		Quit Event:
			Stop the clock from ticking (the app will then close)
		"""
        if isinstance(event, QuitEvent):
            #this will stop the while loop from running
            self.keepGoing = 0
Exemplo n.º 5
0
    def _notify(self, path, backendType, event):
        """
		We notify the filesystem:/directory URI subscribers
		whenever a new entry is created/deleted or a file in this dir is modified.
		
		WARNING/FIXME: the application type may not be correctly
		identified in all case, especially when creating a package forlder,
		as the package.xml is created after the directory...
		"""
        if path.endswith('/'):
            path = path[:-1]
        objectpath, objectname = os.path.split(path)
        if not objectpath:
            objectpath = '/'
        applicationType = self.getApplicationType(objectname, objectpath,
                                                  backendType)
        getLogger().debug("notifying fs change: %s:%s %s (%s)" %
                          (objectpath, objectname, event, applicationType))
        if applicationType:
            uri = 'filesystem:%s' % objectpath
            notification = Messages.Notification("FILE-EVENT", uri, "Xc",
                                                 Versions.getXcVersion())
            notification.setHeader('File-Type', applicationType)
            notification.setHeader('File-Path', objectpath)
            notification.setHeader('File-Name', objectname)
            notification.setHeader('Reason', event)
            EventManager.instance().dispatchNotification(notification)
Exemplo n.º 6
0
 def __init__(self, ev_manager: EventManager):
     '''
     This function is called when the GameEngine is created.
     For more specific objects related to a game instance
         , they should be initialized in GameEngine.initialize()
     '''
     self.ev_manager = ev_manager
     ev_manager.register_listener(self)
     self.state_machine = StateMachine()
Exemplo n.º 7
0
    def __init__(self, ev_manager: EventManager, model: GameEngine):
        '''
        This function is called when the Controller is created.
        For more specific objects related to a game instance
            , they should be initialized in Controller.initialize()
        '''
        self.ev_manager = ev_manager
        ev_manager.register_listener(self)

        self.model = model
Exemplo n.º 8
0
    def __init__(self):
        self.evManager = EventManager()
        self.evManager.RegisterListener(self)

        self.state = Game.STATE_PREPARING
        self.heroes = {}
        self.enemies = {}
        self.enemyCount = 0
        self.problem = (0, 0)
        self.time = 0
        self.solutionWait = 5000  #milliseconds
        self.solEndTime = 0
Exemplo n.º 9
0
    def __init__(self, ev_manager: EventManager, model: GameEngine):
        '''
        This function is called when the GraphicalView is created.
        For more specific objects related to a game instance
            , they should be initialized in GraphicalView.initialize()
        '''
        self.ev_manager = ev_manager
        ev_manager.register_listener(self)

        self.model = model

        self.screen = pg.display.set_mode(Const.WINDOW_SIZE)
        pg.display.set_caption(Const.WINDOW_CAPTION)
        self.background.fill(Const.BACKGROUND_COLOR)
Exemplo n.º 10
0
    def __init__(self, rect, group=None):
        pygame.sprite.Sprite.__init__(self, group)
        self.evManager = EventManager()
        self.evManager.RegisterListener(self)

        self.time = 0

        #self.image = pygame.Surface(rect.size, SRCALPHA)
        self.image = pygame.Surface(rect.size)
        self.image.set_colorkey((0, 0, 0))
        self.image.fill((0, 0, 0, 0))
        self.color = (255, 255, 255)
        self.rect = self.image.get_rect()

        self.hero = None

        #set hud areas
        w = rect.width
        h = rect.height
        self.heroBox = self.image.subsurface(
            (0, 0, w / 2, h * 2 / 3))  #top left box
        #pygame.draw.rect(self.heroBox, self.color, self.heroBox.get_rect(), 4)
        self.DrawBorder(self.heroBox)

        self.enemyBox = self.image.subsurface(
            (w / 2, 0, w / 2, h * 2 / 3))  #top right box
        #pygame.draw.rect(self.enemyBox, self.color, self.enemyBox.get_rect(), 4)
        self.DrawBorder(self.enemyBox)

        self.dataBox = self.image.subsurface((0, h * 2 / 3, w, h / 3))
        #pygame.draw.rect(self.dataBox, self.color, self.dataBox.get_rect(), 4)
        self.DrawBorder(self.dataBox)

        self.solutionBox = self.dataBox.subsurface((50, 50, 100, 50))
        self.timerBox = self.dataBox.subsurface((30, 100, 300, 20))
        self.timer = (0, 0)  #beginning and end of timer

        self.instrBox = self.dataBox.subsurface((200, 20, w / 2, 100))

        #set hud font
        self.font = pygame.font.SysFont("Arial", 18)
        self.font_height = 20

        #initialize instruction text:
        self.instr_wait = "Press SPACE to attack"
        self.instr_prob = "%s \nType solution and press ENTER to solve"
        self.instr_win = "Victory! \nPress SPACE for next battle"
        self.instr_loose = "Game Over! \nPress ESC to quit"
        self.instr = self.instr_wait
        self.sol = ""
Exemplo n.º 11
0
def test():
    listner1 = Listener("thinkroom") #订阅者1
    listner2 = Listener("steve")#订阅者2

    eventManager = EventManager()
    
    #绑定事件和监听器响应函数(新文章)
    eventManager.AddEventListener(EVENT_ARTICAL, listner1.ReadArtical)
    eventManager.AddEventListener(EVENT_ARTICAL, listner2.ReadArtical)
    eventManager.Start()

    publicAcc = PublicAccounts(eventManager)
    timer = Timer(2, publicAcc.WriteNewArtical)
    timer.start()
Exemplo n.º 12
0
def run():

    pygame.init()

    gameWindow = pygame.display.set_mode(
        (GameConfig.screenHight, GameConfig.screenWidth))
    pygame.display.set_caption("Parachutists Game")

    eventManager = EventManager.EventManager()

    planeModel = PlaneModel.PlaneModel(eventManager, GameConfig.screenWidth,
                                       20, 150, 100)  # todo: fix args
    planeController = PlaneController.PlaneController(eventManager, planeModel)
    planeView = PlaneView.PlaneView(eventManager, planeModel, gameWindow)

    boatModel = BoatModel.BoatModel(eventManager,
                                    GameConfig.boatStartXPosition,
                                    GameConfig.boatStartYPosition,
                                    GameConfig.boatWidth, GameConfig.boatHight)
    boatController = BoatController.BoatController(eventManager, boatModel)
    boatView = BoatView.BoatView(eventManager, boatModel, gameWindow)

    gameModel = GameModel.GameModel(eventManager, gameWindow, planeModel)
    gameView = GameView.GameView(eventManager, gameWindow, gameModel)
    gameController = GameController.GameController(eventManager, gameWindow,
                                                   gameModel, planeModel,
                                                   boatModel)
    #gameModel.run()
    gameController.run()
Exemplo n.º 13
0
def main(argv):
    evManager = EventManager.EventManager()
    gamemodel = model.GameEngine(evManager, argv[1:])
    Control = controller.Control(evManager, gamemodel)
    graphics = view.GraphicalView(evManager, gamemodel)
    gamemodel.run()
    return 0
Exemplo n.º 14
0
  def _removeConditions(self, all):
    '''
    Removes registered conditions. All of them if all is True or only one-shot
    conditions if all is False.

    @param all: Remove all conditions (True) or just one-shot conditions
      (False)?
    @type all: boolean
    '''
    for cond, survive in self.conditions.items():
      if not survive or all:
        try:
          EventManager.removeCondition(cond)
          del self.conditions[cond]
        except ValueError:
          pass
Exemplo n.º 15
0
 def __init__(self, port=9999, maximumClient=10):
     print("Initializing Server...")
     start = time.time()
     self.host = socket.gethostbyname(socket.gethostname())
     self.port = port
     self.maximumClient = maximumClient
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.logFileName = 'serverLog'
     self.constant = 'constant'
     self.password = None
     try:
         self.socket.bind((self.host, self.port))
         self.socket.listen(self.maximumClient)
         self.userManager = UserManager()
         #self.projectManager = ProjectManager(self.socket)
         #self.eventManager = EventManager(self.socket)
         self.chatManager = ChatManager(self.userManager)
         self.departmentManager = DepartmentManager(self.userManager)
         self.projectManager = ProjectManager(self.userManager,
                                              self.departmentManager)
         self.eventManager = EventManager(self.userManager,
                                          self.departmentManager)
         print("\n--- Server is Online ---")
         print("IP:", self.host, "Port:", self.port)
         print("Initial Runtime:",
               format((time.time() - start) / 1000, '.10f'), "sec")
         self.thread = threading.Thread(target=self.listen, args=[])
         self.thread.setDaemon(True)
         self.thread.start()
         self.getInformation()
         self.command()
     except OSError as err:
         print(err)
         print("\n!!! Server is already working !!!")
Exemplo n.º 16
0
def main():
    evManager = EventManager.EventManager()
    game = Game.Game(evManager)
    keybd = KeyboardController.KeyboardController(evManager)
    spinner = CPUSpinnerController.CPUSpinnerController(evManager)
    pygameView = PygameView.PygameView(evManager, game)

    spinner.Run()
Exemplo n.º 17
0
    def __init__(self):
        self.evManager = EventManager()
        self.evManager.RegisterListener(self)

        #set up pygame requriements
        pygame.init()
        self.window = pygame.display.set_mode((640, 480))
        pygame.display.set_caption('Mathemagics')
        self.background = pygame.Surface(self.window.get_size())
        self.background.fill((0, 0, 0))

        self.backSprites = pygame.sprite.RenderUpdates()
        self.menuSprites = pygame.sprite.RenderUpdates()
        self.actorSprites = pygame.sprite.RenderUpdates()

        self.mapspr = MapSprite(self.window.get_rect(), self.backSprites)
        self.hud = HUD(self.window.get_rect(), self.menuSprites)
Exemplo n.º 18
0
    def __init__(self, x, y, evID, group=None):
        self.evManager = EventManager()
        self.evManager.RegisterListener(self)

        pygame.sprite.Sprite.__init__(self, group)

        self.evID = evID

        self.pos = (x, y)
        self.InitImages()

        self.image = self.waitImage  #start out waiting

        self.rect = self.image.get_rect()
        self.rect.center = self.pos

        self.healthBox = pygame.Surface((self.rect.width, 15))
        self.healthBox.fill((0, 255, 0))
Exemplo n.º 19
0
 def oneEventInfo(self, i):
     self.ui.setupUi(self.window)
     EventManager.EventInfoDisplay(EventManager.FullEventList[i],
                                   self.ui.textBrowser,
                                   EventManager.FullEventList, i)
     self.window.show()
     self.ui.AddToFavoritesButton.clicked.connect(
         lambda: self.AddToFavorites(i))
     self.ui.AddToCalendarButton.clicked.connect(
         lambda: self.GoogleAddEvent(i))
Exemplo n.º 20
0
 def __init__(self):
     self.logger = logging.getLogger('application.HookEvent')
     self.logger.debug('creating an instance of HookEvent')
     self.hm = pyHook.HookManager()
     self.event_manager = EventManager.EventManager()
     self.monitor = MonitorParams.MonitorParams()
     self.logger.debug('Number of display devices: %s ',
                       str(self.monitor.enum_display_devices()))
     self.logger.debug('Number of physical monitors: %s ',
                       str(self.monitor.get_visible_monitors()))
Exemplo n.º 21
0
def main():
	"""..."""
	evManager = EventManager()
	keyboardMouseGameContController = KeyboardMouseGameContController(evManager)
	controlMapper = ControlMapper(evManager)
	spinner = CPUSpinnerController(evManager)
	pygameView = PygameView(evManager)
	game = Game(evManager)
	game.start()
	spinner.run()
Exemplo n.º 22
0
	def _notifyFileRenamed(self, filename, newName):
		"""
		Filename is the path+name to the previous name, before renaming.
		"""
		if filename.endswith('/'):
			filename = filename[:-1]
		objectpath, objectname = os.path.split(filename)
		if not objectpath:
			objectpath = '/'
		applicationType = self.getApplicationType(newName, objectpath, 'file')
		if applicationType:
			uri = 'filesystem:%s' % objectpath
			notification = Messages.Notification("FILE-EVENT", uri, "Xc", Versions.getXcVersion())
			notification.setHeader('File-Type', applicationType)
			notification.setHeader('File-Path', objectpath)
			notification.setHeader('File-Name', objectname)
			notification.setHeader('Reason', 'renamed')
			notification.setHeader('File-New-Name', newName)
			EventManager.instance().dispatchNotification(notification)
Exemplo n.º 23
0
    def __init__(self, evID, opponents):
        self.evManager = EventManager()
        self.evManager.RegisterListener(self)
        self.evID = evID
        self.opponents = opponents
        self.victim = None

        self.state = ActorModel.STATE_WAITING

        self.AttackWait = 300  #milliseconds
        self.HurtWait = 200  #milliseconds
        self.time = 0
        self.AttackEndTime = self.time
        self.HurtEndTime = self.time

        self.maxHealth = 100
        self.health = self.maxHealth

        self.attackPower = 0  # to be defined in subclasses
Exemplo n.º 24
0
 def __init__(self, config, sku):
     self.config = config
     self.sequence = self.config.Get('TestSequence')
     self.log = Log()
     self.eventManager = EventManager()
     port = self.config.Get('port')
     self.comm = Comm232(self.config, self.log, self.eventManager, port)
     #self.comm.setTimeout(1)
     self.PrepareForInit()
     self.BuildTestItems()
Exemplo n.º 25
0
	def _notifyFileRenamed(self, filename, newName):
		"""
		Filename is the path+name to the previous name, before renaming.
		"""
		if filename.endswith('/'):
			filename = filename[:-1]
		objectpath, objectname = os.path.split(filename)
		if not objectpath:
			objectpath = '/'
		applicationType = self.getApplicationType(newName, objectpath, 'file')
		if applicationType:
			uri = 'filesystem:%s' % objectpath
			notification = Messages.Notification("FILE-EVENT", uri, "Xc", Versions.getXcVersion())
			notification.setHeader('File-Type', applicationType)
			notification.setHeader('File-Path', objectpath)
			notification.setHeader('File-Name', objectname)
			notification.setHeader('Reason', 'renamed')
			notification.setHeader('File-New-Name', newName)
			EventManager.instance().dispatchNotification(notification)
Exemplo n.º 26
0
    def __init__(self):
        self.bots = {}
        self.running = True
        self.events = EventManager.EventHook(self)

        def set_status(event):
            event["bot"].last_status = event["command"]
        self.events.single("received/numeric").hook(set_status)

        self.poll = select.epoll()
        self._random_nicknames = []
Exemplo n.º 27
0
    def __init__(self):
        self.logger = logging.getLogger('application.Handler')
        self.logger.debug('creating an instance of Handler')
        self.event_manager = EventManager.EventManager()
        self.monitor = MonitorParams.MonitorParams()
        self.logger.debug('Number of display devices: %s ',
                          str(self.monitor.enum_display_devices()))
        self.logger.debug('Number of physical monitors: %s ',
                          str(self.monitor.get_visible_monitors()))

        self.stop_play_thread = False
        self.t_play = None
 def __init__(self, globalPtr=0):
     if globalPtr:
         CIntervalManager.__init__(self, None)
         cObj = CIntervalManager.getGlobalPtr()
         self.this = cObj.this
         self.userManagesMemory = 0
     else:
         CIntervalManager.__init__(self)
     self.eventQueue = EventQueue()
     self.eventManager = EventManager.EventManager(self.eventQueue)
     self.setEventQueue(self.eventQueue)
     self.ivals = []
     self.removedIvals = {}
Exemplo n.º 29
0
def main():
    evManager = EventManager.EventManager()
    # Initialize important controllers/listeners
    keybd = Controllers.KeyboardController(evManager)
    spinner = Controllers.CPUSpinnerController(evManager)
    pygameView = Views.PygameView(evManager)
    # --------------------------
    
    game = Game(evManager)
    # Temp Test Code
    #pygameView.SetTrack(game.charactors[0])
    # -------------
    spinner.Run()
Exemplo n.º 30
0
 def __init__(self):
     self.lock = threading.Lock()
     self.args = None
     self.database = None
     self.config = None
     self.bot_directory = os.path.dirname(os.path.realpath(__file__))
     self.servers = {}
     self.running = True
     self.poll = select.epoll()
     self.modules = ModuleManager.ModuleManager(self)
     self.events = EventManager.EventHook(self)
     self.timers = []
     self.events.on("timer").on("reconnect").hook(self.reconnect)
     self.events.on("boot").on("done").hook(self.setup_timers)
Exemplo n.º 31
0
	def _notify(self, path, backendType, event):
		"""
		We notify the filesystem:/directory URI subscribers
		whenever a new entry is created/deleted or a file in this dir is modified.
		
		WARNING/FIXME: the application type may not be correctly
		identified in all case, especially when creating a package forlder,
		as the package.xml is created after the directory...
		"""
		if path.endswith('/'):
			path = path[:-1]
		objectpath, objectname = os.path.split(path)
		if not objectpath:
			objectpath = '/'
		applicationType = self.getApplicationType(objectname, objectpath, backendType)
		getLogger().debug("notifying fs change: %s:%s %s (%s)" % (objectpath, objectname, event, applicationType))
		if applicationType:
			uri = 'filesystem:%s' % objectpath
			notification = Messages.Notification("FILE-EVENT", uri, "Xc", Versions.getXcVersion())
			notification.setHeader('File-Type', applicationType)
			notification.setHeader('File-Path', objectpath)
			notification.setHeader('File-Name', objectname)
			notification.setHeader('Reason', event)
			EventManager.instance().dispatchNotification(notification)
Exemplo n.º 32
0
def start():
    win_offset_y = 25
    os.environ['SDL_VIDEO_WINDOW_POS'] = str(0) + "," + str(win_offset_y)
    pygame.init()
    info_obj = pygame.display.Info()
    #print(info_obj)
    screen_dim = Vec2d(int(info_obj.current_w),
                       int(info_obj.current_h - win_offset_y))

    em = EventManager.EventManager()
    game_engine = GameEngine.GameEngine(em, screen_dim)
    renderer = Renderer.Renderer(em, game_engine, screen_dim)
    controller = Controller.Controller(em, game_engine)

    game_engine.run()
Exemplo n.º 33
0
  def WatchForWindowClose(self, hwnd, name=None, survive=False):
    '''
    Watch for a window to close.

    @param hwnd: Handle of the window that should close
    @type hwnd: number
    @param name: Name of the case where the window actually closes
    @type name: string
    @param survive: Does this watcher survive throughout the macro?
    @type survive: boolean
    '''
    cond = EventManager.addCondition(pyAA.Constants.EVENT_OBJECT_DESTROY,
                                     _onTest, None, Window=hwnd)
    cond.setListener(self.Continue, name)
    self.conditions[cond] = survive
Exemplo n.º 34
0
 def __init__(self):
     self.start_time = time.time()
     self.lock = threading.Lock()
     self.args = None
     self.database = None
     self.config = None
     self.bot_directory = os.path.dirname(os.path.realpath(__file__))
     self.servers = {}
     self.running = True
     self.poll = select.epoll()
     self._events = EventManager.EventHook(self)
     self._exports = Exports.Exports()
     self.modules = ModuleManager.ModuleManager(self, self._events,
                                                self._exports)
     self.log = Logging.Log(self)
     self.line_handler = IRCLineHandler.LineHandler(self, self._events)
     self.timers = []
     self._events.on("timer.reconnect").hook(self.reconnect)
     self._events.on("boot.done").hook(self.setup_timers)
Exemplo n.º 35
0
  def WatchForEvents(self, events, name=None, survive=False, **features):
    '''
    Watches for stated window events with the given features.

    @param events: List of events to watch
    @type events: list
    @param name: Name of the case where the window actually closes
    @type name: string
    @param survive: Does this watcher survive throughout the macro?
    @type survive: boolean
    @param features: Other features to monitor, given by their AA property name
    @type features: dictionary of string, regex, or callable
    '''
    pid = self._getPID()
    # register the features for all events
    for event in events:
      cond = EventManager.addCondition(event, _onTest, pid, **features)
      #cond.setListener(self.Continue, name)
      self._awaitingConditions.append((cond, name))
      self.conditions[cond] = survive
Exemplo n.º 36
0
# -*- coding: utf8 -*-

import events
import inspect

from EventManager import *
from events import *
from handlers import *

# 实例化 EventManager
em = EventManager()
events_dic = dict(inspect.getmembers(events, inspect.isclass))

# 注册 handler
em.add_event_handler(Event1, handler1)
em.add_event_handler(DispatchEvent, dispatchHandler)
em.dispatch_event(DispatchEvent(None))


def serve_forever():
    # 将运行之前的running事件全部清0
    XkEvents.objects.filter(execute_status=EV_RUNNING).update(execute_status=EV_READY)

    while 1:
        # 获得未完成的事件
        try:
            unfinished_ev = XkEvents.objects.get(execute_status=EV_READY)
        except XkEvents.DoesNotExist:
            # print 'No events'
            time.sleep(1)
            continue
Exemplo n.º 37
0
             self.kwargs[k]=line

class EventFake(Event):
    def __init__(self, lines):
        Event.__init__(self,lines)
        self.parse()
        # :) To match The fake date Files:)
        self.name ='test'
        self.args =lines
        
    def parse(self):
         return self.lines
        
         
host, port = 'localhost', 8085                
mgr =EventManager(host, port)
mgr.event_cls =EventFake
handler = EventHandler()


def callback(*args, **kwargs):
    print 'callbackargs', args
    print 'callbackkwargs', kwargs
     
handler.events = {'test': callback}
handler.register(mgr)

while True:
    mgr.serve()
    mgr.monitor(
           error=True ,
Exemplo n.º 38
0
	def _onProbeNotification(self, notification):
		"""
		Called on a new probe/agent notification from the TACS.
		"""
		getLogger().debug("New probe notification: %s" % str(notification))
		EventManager.instance().dispatchNotification(notification)
Exemplo n.º 39
0
	# Now we can daemonize if needed
	if cm.get("ts.daemonize"):
		if pidfile:
			getLogger().info("Daemonizing, using pid file %s..." % pidfile)
		else:
			getLogger().info("Daemonizing...")
		Tools.daemonize(pidFilename = pidfile, displayPid = True)


	# Main start
	cm.set_transient("ts.pid", os.getpid())
	try:
		serverThread = XmlRpcServerThread() # Ws server
		FileSystemManager.initialize()
		EventManager.initialize() # Xc server, Ih server [TSE:CH], Il server [TSE:TL]
		ProbeManager.initialize() # Ia client
		JobManager.initialize() # Job scheduler
		serverThread.start()
		getLogger().info("Started.")
		while 1:
			time.sleep(1)
	except KeyboardInterrupt:
		getLogger().info("Shutting down Testerman Server...")
	except Exception, e:
		sys.stderr.write("Unable to start server: %s\n" % str(e))
		getLogger().critical("Unable to start server: " + str(e))

	serverThread.stop()
	JobManager.finalize()
	ProbeManager.finalize()