Пример #1
0
class DBusThread(threading.Thread):
    """
    DBus server for testing will be ran in separate thread.
    """
    def run(self):
        # Start the main loop
        from dbus.mainloop.glib import DBusGMainLoop
        from gobject import MainLoop
        self.loop = DBusGMainLoop(set_as_default=True)
        dbus.set_default_main_loop(self.loop)
        self.obj = DBusTestObject()
        self.mainloop = MainLoop()
        self.mainloop.run()

    def stop(self):
        self.mainloop.quit()
Пример #2
0
class DBusThread(threading.Thread):
    """
    DBus server for testing will be ran in separate thread.
    """
    def run(self):
        # Start the main loop
        from dbus.mainloop.glib import DBusGMainLoop
        from gobject import MainLoop
        self.loop = DBusGMainLoop(set_as_default=True)
        dbus.set_default_main_loop(self.loop)
        self.obj = DBusTestObject()
        self.mainloop = MainLoop()
        self.mainloop.run()

    def stop(self):
        self.mainloop.quit()
Пример #3
0
class SflPhoneCtrl(Thread):
    """ class for controlling SflPhoned through DBUS

    Classes deriving this class should reimplement signal handlers,
    more especially:
	onIncomingCall_cb
        onCallHangup_cb
        onCallRinging_cb
        onCallHold_cb
        onCallCurrent_cb
        onCallBusy_cb
        onCallFailure_cb
        onConferenceCreated_cb
    """

    # list of active calls (known by the client)
    activeCalls = {}

    # list of active conferences
    activeConferences = {}

    def __init__(self, name=sys.argv[0]):
        Thread.__init__(self)

        # current active account
        self.account = None

        # client name
        self.name = name

	self.currentCallId = ""
        self.currentConfId = ""

	self.isStop = False

        # client registered to sflphoned ?
        self.registered = False
        self.register()

        # Glib MainLoop for processing callbacks
	self.loop = MainLoop()

	gobject.threads_init()


    def __del__(self):
        if self.registered:
            self.unregister()
	self.loop.quit()


    def stopThread(self):
        self.isStop = True


    def register(self):
        if self.registered:
            return

        try:
            # register the main loop for d-bus events
            DBusGMainLoop(set_as_default=True)
            self.bus = dbus.SessionBus()
        except dbus.DBusException, e:
            raise SPdbusError("Unable to connect DBUS session bus")

        dbus_objects = dbus.Interface(self.bus.get_object(
              'org.freedesktop.DBus', '/org/freedesktop/DBus'),
                      'org.freedesktop.DBus').ListNames()

        if not "org.sflphone.SFLphone" in dbus_objects:
            raise SPdbusError("Unable to find org.sflphone.SFLphone in DBUS. Check if sflphoned is running")

        try:
            proxy_instance = self.bus.get_object("org.sflphone.SFLphone",
		 "/org/sflphone/SFLphone/Instance", introspect=False)
            proxy_callmgr = self.bus.get_object("org.sflphone.SFLphone",
		 "/org/sflphone/SFLphone/CallManager", introspect=False)
            proxy_confmgr = self.bus.get_object("org.sflphone.SFLphone",
                 "/org/sflphone/SFLphone/ConfigurationManager",
                        introspect=False)

            self.instance = dbus.Interface(proxy_instance,
                          "org.sflphone.SFLphone.Instance")
            self.callmanager = dbus.Interface(proxy_callmgr,
		          "org.sflphone.SFLphone.CallManager")
            self.configurationmanager = dbus.Interface(proxy_confmgr,
			  "org.sflphone.SFLphone.ConfigurationManager")

        except dbus.DBusException, e:

            raise SPdbusError("Unable to bind to sflphoned api, ask core-dev team to implement getVersion method and start to pray.")
Пример #4
0
class SflPhoneCtrlSimple(Thread):
    """ Simple class for controlling SflPhoned through DBUS

        If option testSuite (ts) is put to true, 
	simple actions are implemented on incoming call.
    """ 

    # list of active calls (known by the client)
    activeCalls = {}

    def __init__(self, test=False, name=sys.argv[0]):
        print "Create SFLphone instance"
	Thread.__init__(self)
       	# current active account
        self.account = None
        # client name
        self.name = name
        # client registered to sflphoned ?
        self.registered = False
        self.register()
	self.currentCallId = ""

	self.loop = MainLoop()

	self.isStop = False

	self.test = test
	self.onIncomingCall_cb = None
	self.event = Event()

	gobject.threads_init()
	


    def __del__(self):
        if self.registered:
            self.unregister()
	self.loop.quit()


    def stopThread(self):
        print "Stop PySFLphone"
        self.isStop = True
	


    def register(self):
        if self.registered:
            return

        try:
            # register the main loop for d-bus events
            DBusGMainLoop(set_as_default=True)
            self.bus = dbus.SessionBus()
        except dbus.DBusException, e:
            raise SPdbusError("Unable to connect DBUS session bus")

        dbus_objects = dbus.Interface(self.bus.get_object(
              'org.freedesktop.DBus', '/org/freedesktop/DBus'), 
                      'org.freedesktop.DBus').ListNames()

        if not "org.sflphone.SFLphone" in dbus_objects:
            raise SPdbusError("Unable to find org.sflphone.SFLphone in DBUS. Check if sflphoned is running")

        try:
            proxy_instance = self.bus.get_object("org.sflphone.SFLphone",
		 "/org/sflphone/SFLphone/Instance", introspect=False)
            proxy_callmgr = self.bus.get_object("org.sflphone.SFLphone",
		 "/org/sflphone/SFLphone/CallManager", introspect=False)
            proxy_confmgr = self.bus.get_object("org.sflphone.SFLphone", 
                 "/org/sflphone/SFLphone/ConfigurationManager", 
                        introspect=False)

            self.instance = dbus.Interface(proxy_instance,
                          "org.sflphone.SFLphone.Instance")
            self.callmanager = dbus.Interface(proxy_callmgr,
		          "org.sflphone.SFLphone.CallManager")
            self.configurationmanager = dbus.Interface(proxy_confmgr,
			  "org.sflphone.SFLphone.ConfigurationManager")

        except dbus.DBusException, e:
            
            raise SPdbusError("Unable to bind to sflphoned api, ask core-dev team to implement getVersion method and start to pray.")
Пример #5
0
class HTTPServer(SoupServer):
    def __init__(self,
                 address='',
                 port=8080,
                 access_log=None,
                 pid_file=None,
                 profile=None):
        SoupServer.__init__(self, address=address, port=port)

        # Keep arguments
        self.address = address
        self.port = port
        self.access_log = access_log
        self.pid_file = pid_file
        self.profile = profile

        # Main Loop
        self.main_loop = MainLoop()

        # Open log files
        if access_log is not None:
            self.access_log_file = open(access_log, 'a+')

    #######################################################################
    # Logging
    #######################################################################
    def log_access(self, line):
        # Default: stdout
        if self.access_log is None:
            stdout.write(line)
            return

        # File
        log = self.access_log_file
        if fstat(log.fileno())[3] == 0:
            log = open(self.access_log, 'a+')
            self.access_log_file = log
        log.write(line)
        log.flush()

    #######################################################################
    # Start & Stop
    #######################################################################
    def start(self):
        # Language negotiation
        from itools.web import select_language
        init_language_selector(select_language)

        # Graceful stop
        signal(SIGINT, self.stop_gracefully)
        signal(SIGTERM, self.zap)
        if self.pid_file:
            pid = getpid()
            open(self.pid_file, 'w').write(str(pid))

        # Run
        SoupServer.start(self)
        print 'Listen %s:%d' % (self.address, self.port)
        if self.profile:
            runctx("self.main_loop.run()", globals(), locals(), self.profile)
        else:
            self.main_loop.run()

    def stop_gracefully(self, signum, frame):
        """Inmediately stop accepting new connections, and quit once there
        are not more ongoing requests.
        """
        # TODO Implement the graceful part

        # Quit
        print 'Shutting down the server (gracefully)...'
        self.stop()

    def zap(self, signum, frame):
        print 'Shutting down the server...'
        self.stop()

    def stop(self):
        SoupServer.stop(self)
        self.main_loop.quit()
        if self.pid_file:
            remove_file(self.pid_file)
        if self.access_log:
            self.access_log_file.close()

    #######################################################################
    # Callbacks
    #######################################################################
    known_methods = [
        'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'LOCK', 'UNLOCK'
    ]

    def star_callback(self, soup_message, path):
        """This method is called for the special "*" request URI, which means
        the request concerns the server itself, and not any particular
        resource.

        Currently this feature is only supported for the OPTIONS request
        method:

          OPTIONS * HTTP/1.1
        """
        method = soup_message.get_method()
        if method != 'OPTIONS':
            soup_message.set_status(405)
            soup_message.set_header('Allow', 'OPTIONS')
            return

        methods = self.known_methods
        soup_message.set_status(200)
        soup_message.set_header('Allow', ','.join(methods))

    def path_callback(self, soup_message, path):
        raise NotImplementedError
Пример #6
0
class HTTPServer(SoupServer):

    def __init__(self, address='', port=8080, access_log=None, pid_file=None,
                 profile=None):
        SoupServer.__init__(self, address=address, port=port)

        # Keep arguments
        self.address = address
        self.port = port
        self.access_log = access_log
        self.pid_file = pid_file
        self.profile = profile

        # Main Loop
        self.main_loop = MainLoop()

        # Open log files
        if access_log is not None:
            self.access_log_file = open(access_log, 'a+')


    #######################################################################
    # Logging
    #######################################################################
    def log_access(self, line):
        # Default: stdout
        if self.access_log is None:
            stdout.write(line)
            return

        # File
        log = self.access_log_file
        if fstat(log.fileno())[3] == 0:
            log = open(self.access_log, 'a+')
            self.access_log_file = log
        log.write(line)
        log.flush()


    #######################################################################
    # Start & Stop
    #######################################################################
    def start(self):
        # Language negotiation
        from itools.web import select_language
        init_language_selector(select_language)

        # Graceful stop
        signal(SIGINT, self.stop_gracefully)
        signal(SIGTERM, self.zap)
        if self.pid_file:
            pid = getpid()
            open(self.pid_file, 'w').write(str(pid))

        # Run
        SoupServer.start(self)
        print 'Listen %s:%d' % (self.address, self.port)
        if self.profile:
            runctx("self.main_loop.run()", globals(), locals(), self.profile)
        else:
            self.main_loop.run()


    def stop_gracefully(self, signum, frame):
        """Inmediately stop accepting new connections, and quit once there
        are not more ongoing requests.
        """
        # TODO Implement the graceful part

        # Quit
        print 'Shutting down the server (gracefully)...'
        self.stop()


    def zap(self, signum, frame):
        print 'Shutting down the server...'
        self.stop()


    def stop(self):
        SoupServer.stop(self)
        self.main_loop.quit()
        if self.pid_file:
            remove_file(self.pid_file)
        if self.access_log:
            self.access_log_file.close()


    #######################################################################
    # Callbacks
    #######################################################################
    known_methods = [
        'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'LOCK', 'UNLOCK']


    def star_callback(self, soup_message, path):
        """This method is called for the special "*" request URI, which means
        the request concerns the server itself, and not any particular
        resource.

        Currently this feature is only supported for the OPTIONS request
        method:

          OPTIONS * HTTP/1.1
        """
        method = soup_message.get_method()
        if method != 'OPTIONS':
            soup_message.set_status(405)
            soup_message.set_header('Allow', 'OPTIONS')
            return

        methods = self.known_methods
        soup_message.set_status(200)
        soup_message.set_header('Allow', ','.join(methods))


    def path_callback(self, soup_message, path):
        raise NotImplementedError
Пример #7
0
class SflPhoneCtrlSimple(Thread):
    """ Simple class for controlling SflPhoned through DBUS

        If option testSuite (ts) is put to true, 
	simple actions are implemented on incoming call.
    """

    # list of active calls (known by the client)
    activeCalls = {}

    def __init__(self, test=False, name=sys.argv[0]):
        print "Create SFLphone instance"
        Thread.__init__(self)
        # current active account
        self.account = None
        # client name
        self.name = name
        # client registered to sflphoned ?
        self.registered = False
        self.register()
        self.currentCallId = ""

        self.loop = MainLoop()

        self.isStop = False

        self.test = test
        self.onIncomingCall_cb = None
        self.event = Event()

        gobject.threads_init()

    def __del__(self):
        if self.registered:
            self.unregister()
        self.loop.quit()

    def stopThread(self):
        print "Stop PySFLphone"
        self.isStop = True

    def register(self):
        if self.registered:
            return

        try:
            # register the main loop for d-bus events
            DBusGMainLoop(set_as_default=True)
            self.bus = dbus.SessionBus()
        except dbus.DBusException, e:
            raise SPdbusError("Unable to connect DBUS session bus")

        dbus_objects = dbus.Interface(
            self.bus.get_object('org.freedesktop.DBus',
                                '/org/freedesktop/DBus'),
            'org.freedesktop.DBus').ListNames()

        if not "org.sflphone.SFLphone" in dbus_objects:
            raise SPdbusError(
                "Unable to find org.sflphone.SFLphone in DBUS. Check if sflphoned is running"
            )

        try:
            proxy_instance = self.bus.get_object(
                "org.sflphone.SFLphone",
                "/org/sflphone/SFLphone/Instance",
                introspect=False)
            proxy_callmgr = self.bus.get_object(
                "org.sflphone.SFLphone",
                "/org/sflphone/SFLphone/CallManager",
                introspect=False)
            proxy_confmgr = self.bus.get_object(
                "org.sflphone.SFLphone",
                "/org/sflphone/SFLphone/ConfigurationManager",
                introspect=False)

            self.instance = dbus.Interface(proxy_instance,
                                           "org.sflphone.SFLphone.Instance")
            self.callmanager = dbus.Interface(
                proxy_callmgr, "org.sflphone.SFLphone.CallManager")
            self.configurationmanager = dbus.Interface(
                proxy_confmgr, "org.sflphone.SFLphone.ConfigurationManager")

        except dbus.DBusException, e:

            raise SPdbusError(
                "Unable to bind to sflphoned api, ask core-dev team to implement getVersion method and start to pray."
            )
Пример #8
0
class RTSPserver:
	"""
	GStreamer RTSP server.
	"""
	def __init__(self, port, bitrate, framerate):
		"""
		**On init:** Some initialization code.
		
		:param integer port: RTSP server port.
		:param integer bitrate: Video bitrate.
		:param integer framerate: Video framerate.
		"""
		self.bitrate = bitrate
		self.framerate = framerate
		self.server = Server()
		self.loop = None
		self.server.set_service(str(port))
		self.factory = []
		self.__addMedia()
	
	def __addFactory(self,url,factory):
		mmap = self.server.get_media_mapping()
		self.factory.append(factory)
		mmap.add_factory(url,factory)
		self.server.set_media_mapping(mmap)
		print "Add Service rtsp://"+socket.gethostname()+":" + self.server.get_service() + url

	def __addMedia(self):
		"""
		videotest
		"""                                
		launch = "videotestsrc pattern=ball ! timeoverlay halign=right valign=top ! clockoverlay halign=left valign=top time-format=\"%Y/%m/%d %H:%M:%S\" ! "
		launch += "x264enc bitrate="+str(self.bitrate)+" ! rtph264pay name=pay0"                
		mfactory = MediaFactory()
		mfactory.set_launch(launch)
		mfactory.set_shared(True)
		mfactory.set_eos_shutdown(True)
		self.__addFactory("/videotest.h264", mfactory)

		"""
		webcam
		"""
		launch = "v4l2src ! video/x-raw-yuv,width=320,height=240,depth=32,framerate="+str(self.framerate)+"/1 ! timeoverlay halign=right valign=top ! clockoverlay halign=left valign=top time-format=\"%Y/%m/%d %H:%M:%S\" ! queue ! "
		launch += "x264enc bitrate="+str(self.bitrate)+" ! rtph264pay name=pay0"                
		mfactory = MediaFactory()
		mfactory.set_launch(launch)
		mfactory.set_shared(True)
		mfactory.set_eos_shutdown(True)
		self.__addFactory("/v4l2.h264", mfactory)
		
	
	def run(self):
		"""
		Attach server and run the loop (see :attr:`loop`).
		"""
		if self.server.attach():
			self.loop = MainLoop()
			self.loop.run()
	
	def stop(self):
		self.loop.quit()