def loginButtonClicked(self): from gobject import MainLoop from dbus.mainloop.glib import DBusGMainLoop from ubuntuone.platform.credentials import CredentialsManagementTool DBusGMainLoop(set_as_default=True) loop = MainLoop() def loginQuit(result): loop.quit() self.service['ubuntuOneInst'] = result self.service['auth'] = result != None if self.service['auth']: self.serviceModel.notifyAuthChanged() cd = CredentialsManagementTool() d = cd.login() d.addCallbacks(loginQuit) loop.run() isAuth = self.service['auth'] self.ui.loginButton.setVisible(not isAuth) self.ui.successLabel.setVisible(isAuth) self.ui.volumeSettings.setVisible(isAuth) if isAuth: self.ui.volumeEdit.setFocus()
def run(self): """ Attach server and run the loop (see :attr:`loop`). """ if self.server.attach(): self.loop = MainLoop() self.loop.run()
def log_in_or_out(login): MainLoop,DBusGMainLoop,CredentialsManagementTool = import_globals() global _login_success _login_success = False DBusGMainLoop(set_as_default=True) loop = MainLoop() def quit(result): global _login_success loop.quit() if result: _login_success = True cd = CredentialsManagementTool() if login: d = cd.login() else: d = cd.clear_credentials() d.addCallbacks(quit) loop.run() if not _login_success and login: sys.exit(1)
def main_pyneo(): """This is the function that will be used to launch pypimd for pyneo""" log_open('pypimd', LOG_NDELAY|LOG_PID|LOG_PERROR, LOG_DAEMON) DBusGMainLoop(set_as_default=True) # Claim the bus name # TODO Check for exceptions SystemBus().request_name(DBUS_BUS_NAME_PYNEO) # Workaround for relative imports of pyneod stuff, see # http://mail.python.org/pipermail/python-list/2007-May/438250.html sys.path.append('/usr/share/pyneod') from backend_manager import BackendManager from domain_manager import DomainManager # Load plugins DomainManager.init(os.getcwdu()) BackendManager(os.getcwdu()) # 3-2-1-Go! main_loop = MainLoop() main_loop.run() log_close() return 0
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 __play(self): """ Attach event handler, set state to *playing* and run the loop (see :attr:`loop`). """ self.pipeline.get_bus().add_watch(self.__events) self.pipeline.set_state(STATE_PLAYING) self.loop = MainLoop() self.loop.run() VTLOG.debug("GStreamer: Loop stopped")
def main(): # Se establece que D-Bus utilizará como ciclo de mensajes por defecto # al que provee Glib DBusGMainLoop(set_as_default=True) # Se instancia el objeto que procesará la señal proveniente de UDisks autoplayer = AutoPlayer() # Se instancia y pone a correr el ciclo de mensajes en espera de la emisión # de la señal de UDisks mainloop = MainLoop() mainloop.run()
def logout(): from gobject import MainLoop from dbus.mainloop.glib import DBusGMainLoop from ubuntuone.platform.credentials import CredentialsManagementTool DBusGMainLoop(set_as_default=True) loop = MainLoop() def quit(result): loop.quit() cd = CredentialsManagementTool() d = cd.clear_credentials() d.addCallbacks(quit) loop.run()
def monitor(output='syslog'): bus = SystemBus() logger = DBusLogger(output) bus.add_match_string("") bus.add_message_filter(logger) loop = MainLoop() print "Press Ctrl-C to stop." try: loop.run() except: print " Loop exited" bus.remove_message_filter(logger) bus.remove_match_string("")
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()
def main(argv): global localSettings logging.getLogger().setLevel(logging.INFO) parser = argparse.ArgumentParser() parser.add_argument('--path', help = 'use given dir as data directory', default = ".") parser.add_argument('--no-delay', action = 'store_true', help = "don't delay storing the settings (used by the test script)") parser.add_argument('-v', '--version', action = 'store_true', help = "returns the program version") args = parser.parse_args(argv) if args.version: print("v%01x.%02x" % (FIRMWARE_VERSION_MAJOR, FIRMWARE_VERSION_MINOR)) sys.exit() if args.path[-1] != '/': args.path += "/" print("localsettings v%01x.%02x starting up " % (FIRMWARE_VERSION_MAJOR, FIRMWARE_VERSION_MINOR)) DBusGMainLoop(set_as_default=True) localSettings = LocalSettings(args.path, 0 if args.no_delay else 2) # load system default settings, note need localSettings to be ready loadSettingsDir(localSettings.sysSettingsDir, localSettings.settingsGroup) MainLoop().run()
class Main(): # Run the loop and classes DBusGMainLoop(set_as_default=True) g = GoogleAPI() y = YahooAPI() n = NoaaAPI() a = Application() a.ready() mainloop = MainLoop() mainloop.run()
def login(self): from gobject import MainLoop from dbus.mainloop.glib import DBusGMainLoop from ubuntuone.platform.credentials import CredentialsManagementTool self.login_success = False DBusGMainLoop(set_as_default=True) loop = MainLoop() def quit(result): loop.quit() if result: self.login_success = True cd = CredentialsManagementTool() d = cd.login() d.addCallbacks(quit) loop.run() return self.login_success
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+')
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 login(): from gobject import MainLoop from dbus.mainloop.glib import DBusGMainLoop from ubuntuone.platform.credentials import CredentialsManagementTool global _login_success _login_success = False DBusGMainLoop(set_as_default=True) loop = MainLoop() def quit(result): global _login_success loop.quit() if result: _login_success = True cd = CredentialsManagementTool() d = cd.login() d.addCallbacks(quit) loop.run() if not _login_success: sys.exit(1)
def run(write_pipe1=None, # write pipe to systemtray write_pipe2=None, # write pipe to hpdio read_pipe3=None): # read pipe from hpdio global dbus_loop, main_loop global system_bus, session_bus global w1, w2, r3 log.set_module("hp-systray(hpssd)") log.debug("PID=%d" % os.getpid()) w1, w2, r3 = write_pipe1, write_pipe2, read_pipe3 dbus_loop = DBusGMainLoop(set_as_default=True) main_loop = MainLoop() try: system_bus = SystemBus(mainloop=dbus_loop) except dbus.exceptions.DBusException, e: log.error("Unable to connect to dbus system bus. Exiting.") sys.exit(1)
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()
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.")
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.")
class RTSPserver: """ GStreamer RTSP server. """ def __init__(self, port, bitrate, framerate, path, videos): """ **On init:** Some initialization code. :param port: RTSP server port. :type port: string or integer :param bitrate: The bitrate (in kbps). :type bitrate: string or integer :param framerate: The framerate (in fps). :type framerate: string or integer :param string path: Path to the video directory. :param list videos: List of available videos. """ #: The bitrate (in kbps). self.bitrate = bitrate #: The framerate (in fps). self.framerate = framerate #: Path to the video directory. self.path = path #: List of available videos. self.videos = videos #: GStreamer RTSP server instance. self.server = Server() #: Gstreamer loop. self.loop = None self.server.set_service(str(port)) #: List of GStreamer RTSP factories. self.factory = [] self.__addMedia() def __addMedia(self): """ Add media to server. """ for i, video in enumerate(self.videos): for j in range(0, 4): launch = "filesrc location="+self.path+"/"+video+" ! decodebin ! videorate ! video/x-raw-yuv,framerate="+str(self.framerate)+"/1 ! " launch += { 0: "ffenc_h263 bitrate="+str(self.bitrate)+"000 ! rtph263pay name=pay0", 1: "x264enc bitrate="+str(self.bitrate)+" ! rtph264pay name=pay0", 2: "ffenc_mpeg4 bitrate="+str(self.bitrate)+"000 ! rtpmp4vpay name=pay0", 3: "theoraenc bitrate="+str(self.bitrate)+" ! rtptheorapay name=pay0" }[j] mmap = self.server.get_media_mapping() self.factory.append(MediaFactory()) self.factory[-1].set_launch(launch) self.factory[-1].set_shared(True) self.factory[-1].set_eos_shutdown(True) name = { 0: "/video"+str(i)+".h263", 1: "/video"+str(i)+".h264", 2: "/video"+str(i)+".mpeg4", 3: "/video"+str(i)+".theora" }[j] mmap.add_factory(name, self.factory[-1]) self.server.set_media_mapping(mmap) def run(self): """ Attach server and run the loop (see :attr:`loop`). """ if self.server.attach(): self.loop = MainLoop() self.loop.run()
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
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." )
class RTSPclient: """ GStreamer RTSP client. """ def __init__(self, conf, video): """ **On init:** Some initialization code. :param dictionary conf: Parsed configuration file. :param string video: Path to the selected video. """ #: Dictionary of configuration options (see :attr:`VideoTester.core.Client.conf`). self.conf = conf #: Path to the selected video (see :attr:`VideoTester.core.Client.video`). self.video = video #: Video size: ``(width, height)``. self.size = None #: Dictionary of paths to the processed video files: ``{'original':[<compressed>, <yuv>], 'coded':[<compressed>, <yuv>], 'received':[<compressed>, <yuv>]}``. self.files = {'original': [], 'coded': [], 'received': []} #: Gstreamer pipeline. self.pipeline = None #: Gstreamer loop. self.loop = None #: Selected video URL. self.url = 'rtsp://' + self.conf['ip'] + ':' + self.conf[ 'rtspport'] + '/' + self.conf['video'] + '.' + self.conf['codec'] self.encoder, self.depay, self.bitrate, self.__add = { 'h263': ("ffenc_h263", "rtph263depay", self.conf['bitrate'] + '000', ''), 'h264': ("x264enc", "rtph264depay", self.conf['bitrate'], ''), 'mpeg4': ("ffenc_mpeg4", "rtpmp4vdepay", self.conf['bitrate'] + '000', ''), 'theora': ("theoraenc", "rtptheoradepay ! theoraparse", self.conf['bitrate'], ' ! matroskamux') }[self.conf['codec']] def __events(self, bus, msg): """ Event handler. :param bus: Gstreamer bus object. :param msg: Gstreamer message object. :returns: True. :rtype: boolean """ t = msg.type if t == MESSAGE_EOS: self.pipeline.set_state(STATE_PAUSED) sleep(0.5) self.pipeline.set_state(STATE_READY) self.pipeline.set_state(STATE_NULL) VTLOG.debug("GStreamer: MESSAGE_EOS received") self.loop.quit() elif t == MESSAGE_ERROR: self.pipeline.set_state(STATE_PAUSED) sleep(0.5) self.pipeline.set_state(STATE_READY) self.pipeline.set_state(STATE_NULL) e, d = msg.parse_error() VTLOG.error("GStreamer: MESSAGE_ERROR received") VTLOG.error(e) self.loop.quit() return True def __play(self): """ Attach event handler, set state to *playing* and run the loop (see :attr:`loop`). """ self.pipeline.get_bus().add_watch(self.__events) self.pipeline.set_state(STATE_PLAYING) self.loop = MainLoop() self.loop.run() VTLOG.debug("GStreamer: Loop stopped") def receiver(self): """ Connect to the RTSP server and receive the selected video (see :attr:`video`). """ VTLOG.info("Starting GStreamer receiver...") self.pipeline = parse_launch( 'rtspsrc name=source ! tee name=t ! queue ! ' + self.depay + self.__add + ' ! filesink name=sink1 t. ! queue \ ! decodebin ! videorate skip-to-first=True ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1 ! filesink name=sink2') source = self.pipeline.get_by_name('source') sink1 = self.pipeline.get_by_name('sink1') sink2 = self.pipeline.get_by_name('sink2') source.props.location = self.url source.props.protocols = self.conf['protocols'] location = self.conf['tempdir'] + self.conf['num'] + '.' + self.conf[ 'codec'] self.files['received'].append(location) sink1.props.location = location location = self.conf['tempdir'] + self.conf['num'] + '.yuv' self.files['received'].append(location) sink2.props.location = location pad = sink2.get_pad("sink") pad.connect("notify::caps", self.__notifyCaps) self.__play() VTLOG.info("GStreamer receiver stopped") def reference(self): """ Make the reference videos. :returns: Paths to video files (see :attr:`files`) and video size (see :attr:`size`). :rtype: tuple """ VTLOG.info("Making reference...") self.pipeline = parse_launch( 'filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1 ! filesink name=sink1') source = self.pipeline.get_by_name('source') sink1 = self.pipeline.get_by_name('sink1') location = self.video self.files['original'].append(location) source.props.location = location location = self.conf['tempdir'] + self.conf['num'] + '_ref_original.yuv' self.files['original'].append(location) sink1.props.location = location self.__play() self.pipeline = parse_launch('filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1 ! ' + self.encoder + ' bitrate=' + self.bitrate \ + ' ! tee name=t ! queue' + self.__add + ' ! filesink name=sink2 t. ! queue ! decodebin ! filesink name=sink3') source = self.pipeline.get_by_name('source') sink2 = self.pipeline.get_by_name('sink2') sink3 = self.pipeline.get_by_name('sink3') location = self.video source.props.location = location location = self.conf['tempdir'] + self.conf[ 'num'] + '_ref.' + self.conf['codec'] self.files['coded'].append(location) sink2.props.location = location location = self.conf['tempdir'] + self.conf['num'] + '_ref.yuv' self.files['coded'].append(location) sink3.props.location = location self.__play() VTLOG.info("Reference made") return self.files, self.size def __notifyCaps(self, pad, args): """ Write caps to a file. :param pad: Gstreamer pad object. :param args: Other arguments. """ caps = pad.get_negotiated_caps() if caps: caps = caps.to_string() aux = caps.split(', ') for x in aux: if x.find('width') != -1: width = int(x[11:len(x)]) elif x.find('height') != -1: height = int(x[12:len(x)]) self.size = (width, height) f = open(self.conf['tempdir'] + self.conf['num'] + '_caps.txt', "wb") f.write(caps) f.close()
def listen(self): from gobject import MainLoop loop = MainLoop() loop.run()
def main(): __start() from gobject import MainLoop MainLoop().run() return
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
# monitor zeitgeist and do stuff from zeitgeist.client import ZeitgeistClient from zeitgeist.datamodel import TimeRange, Event from gobject import MainLoop #import hamster.client class e_handler: def handler(self, tr, ev): # because the mainloop appears to catch exceptions from traceback import print_exc from urlparse import urlparse try: # FIXME insert clever rules here app = urlparse(ev[0].actor).netloc #desk = open("/usr/share/applications/" + app) #comments = filter(lambda x: x.startswith("Comment[en_GB]="), desk) #comment = comments[0].split("=")[1].strip() #self.add_fact(comment + " - " + ev[0].subjects[0].text) print(ev[0].subjects[0].text) except: print_exc() hh = e_handler() ml = MainLoop() ZeitgeistClient().install_monitor( TimeRange.from_now(), [Event()], hh.handler, hh.handler) ml.run()
class RTSPserver: """ GStreamer RTSP server. """ def __init__(self, port, bitrate, framerate, path, videos): """ **On init:** Some initialization code. :param port: RTSP server port. :type port: string or integer :param bitrate: The bitrate (in kbps). :type bitrate: string or integer :param framerate: The framerate (in fps). :type framerate: string or integer :param string path: Path to the video directory. :param list videos: List of available videos. """ #: The bitrate (in kbps). self.bitrate = bitrate #: The framerate (in fps). self.framerate = framerate #: Path to the video directory. self.path = path #: List of available videos. self.videos = videos #: GStreamer RTSP server instance. self.server = Server() #: Gstreamer loop. self.loop = None self.server.set_service(str(port)) #: List of GStreamer RTSP factories. self.factory = [] self.__addMedia() def __addMedia(self): """ Add media to server. """ for i, video in enumerate(self.videos): for j in range(0, 4): launch = "filesrc location=" + self.path + "/" + video + " ! decodebin ! videorate ! video/x-raw-yuv,framerate=" + str( self.framerate) + "/1 ! " launch += { 0: "ffenc_h263 bitrate=" + str(self.bitrate) + "000 ! rtph263pay name=pay0", 1: "x264enc bitrate=" + str(self.bitrate) + " ! rtph264pay name=pay0", 2: "ffenc_mpeg4 bitrate=" + str(self.bitrate) + "000 ! rtpmp4vpay name=pay0", 3: "theoraenc bitrate=" + str(self.bitrate) + " ! rtptheorapay name=pay0" }[j] mmap = self.server.get_media_mapping() self.factory.append(MediaFactory()) self.factory[-1].set_launch(launch) self.factory[-1].set_shared(True) self.factory[-1].set_eos_shutdown(True) name = { 0: "/video" + str(i) + ".h263", 1: "/video" + str(i) + ".h264", 2: "/video" + str(i) + ".mpeg4", 3: "/video" + str(i) + ".theora" }[j] mmap.add_factory(name, self.factory[-1]) self.server.set_media_mapping(mmap) def run(self): """ Attach server and run the loop (see :attr:`loop`). """ if self.server.attach(): self.loop = MainLoop() self.loop.run()
def dbus_loop(actor): threads_init() mainloop = MainLoop() actor.set_event_loop(mainloop) actor.start() mainloop.run()
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()
class RTSPclient: """ GStreamer RTSP client. """ def __init__(self, conf, video): """ **On init:** Some initialization code. :param dictionary conf: Parsed configuration file. :param string video: Path to the selected video. """ #: Dictionary of configuration options (see :attr:`VideoTester.core.Client.conf`). self.conf = conf #: Path to the selected video (see :attr:`VideoTester.core.Client.video`). self.video = video #: Video size: ``(width, height)``. self.size = None #: Dictionary of paths to the processed video files: ``{'original':[<compressed>, <yuv>], 'coded':[<compressed>, <yuv>], 'received':[<compressed>, <yuv>]}``. self.files = {'original':[], 'coded':[], 'received':[]} #: Gstreamer pipeline. self.pipeline = None #: Gstreamer loop. self.loop = None #: Selected video URL. self.url = 'rtsp://' + self.conf['ip'] + ':' + self.conf['rtspport'] + '/' + self.conf['video'] + '.' + self.conf['codec'] self.encoder, self.depay, self.bitrate, self.__add = { 'h263': ("ffenc_h263", "rtph263depay", self.conf['bitrate'] + '000', ''), 'h264': ("x264enc", "rtph264depay", self.conf['bitrate'], ''), 'mpeg4': ("ffenc_mpeg4", "rtpmp4vdepay", self.conf['bitrate'] + '000', ''), 'theora': ("theoraenc", "rtptheoradepay ! theoraparse", self.conf['bitrate'], ' ! matroskamux') }[self.conf['codec']] def __events(self, bus, msg): """ Event handler. :param bus: Gstreamer bus object. :param msg: Gstreamer message object. :returns: True. :rtype: boolean """ t = msg.type if t == MESSAGE_EOS: self.pipeline.set_state(STATE_PAUSED) sleep(0.5) self.pipeline.set_state(STATE_READY) self.pipeline.set_state(STATE_NULL) VTLOG.debug("GStreamer: MESSAGE_EOS received") self.loop.quit() elif t == MESSAGE_ERROR: self.pipeline.set_state(STATE_PAUSED) sleep(0.5) self.pipeline.set_state(STATE_READY) self.pipeline.set_state(STATE_NULL) e, d = msg.parse_error() VTLOG.error("GStreamer: MESSAGE_ERROR received") VTLOG.error(e) self.loop.quit() return True def __play(self): """ Attach event handler, set state to *playing* and run the loop (see :attr:`loop`). """ self.pipeline.get_bus().add_watch(self.__events) self.pipeline.set_state(STATE_PLAYING) self.loop = MainLoop() self.loop.run() VTLOG.debug("GStreamer: Loop stopped") def receiver(self): """ Connect to the RTSP server and receive the selected video (see :attr:`video`). """ VTLOG.info("Starting GStreamer receiver...") self.pipeline = parse_launch('rtspsrc name=source ! tee name=t ! queue ! ' + self.depay + self.__add + ' ! filesink name=sink1 t. ! queue \ ! decodebin ! videorate skip-to-first=True ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1 ! filesink name=sink2') source = self.pipeline.get_by_name('source') sink1 = self.pipeline.get_by_name('sink1') sink2 = self.pipeline.get_by_name('sink2') source.props.location = self.url source.props.protocols = self.conf['protocols'] location = self.conf['tempdir'] + self.conf['num'] + '.' + self.conf['codec'] self.files['received'].append(location) sink1.props.location = location location = self.conf['tempdir'] + self.conf['num'] + '.yuv' self.files['received'].append(location) sink2.props.location = location pad = sink2.get_pad("sink") pad.connect("notify::caps", self.__notifyCaps) self.__play() VTLOG.info("GStreamer receiver stopped") def reference(self): """ Make the reference videos. :returns: Paths to video files (see :attr:`files`) and video size (see :attr:`size`). :rtype: tuple """ VTLOG.info("Making reference...") self.pipeline = parse_launch('filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1 ! filesink name=sink1') source = self.pipeline.get_by_name('source') sink1 = self.pipeline.get_by_name('sink1') location = self.video self.files['original'].append(location) source.props.location = location location = self.conf['tempdir'] + self.conf['num'] + '_ref_original.yuv' self.files['original'].append(location) sink1.props.location = location self.__play() self.pipeline = parse_launch('filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1 ! ' + self.encoder + ' bitrate=' + self.bitrate \ + ' ! tee name=t ! queue' + self.__add + ' ! filesink name=sink2 t. ! queue ! decodebin ! filesink name=sink3') source = self.pipeline.get_by_name('source') sink2 = self.pipeline.get_by_name('sink2') sink3 = self.pipeline.get_by_name('sink3') location = self.video source.props.location = location location = self.conf['tempdir'] + self.conf['num'] + '_ref.' + self.conf['codec'] self.files['coded'].append(location) sink2.props.location = location location = self.conf['tempdir'] + self.conf['num'] + '_ref.yuv' self.files['coded'].append(location) sink3.props.location = location self.__play() VTLOG.info("Reference made") return self.files, self.size def __notifyCaps(self, pad, args): """ Write caps to a file. :param pad: Gstreamer pad object. :param args: Other arguments. """ caps = pad.get_negotiated_caps() if caps: caps = caps.to_string() aux = caps.split(', ') for x in aux: if x.find('width') != -1: width = int(x[11:len(x)]) elif x.find('height') != -1: height = int(x[12:len(x)]) self.size = (width, height) f = open(self.conf['tempdir'] + self.conf['num'] + '_caps.txt', "wb") f.write(caps) f.close()
# Copyright (c) Benjamin Kietzman (github.com/bkietz) # # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) import dbus from dbus.mainloop.glib import DBusGMainLoop from gobject import MainLoop bus_name = 'com.example.Sample' session_bus = dbus.SessionBus(mainloop=DBusGMainLoop()) example_remote = session_bus.get_object(bus_name, '/path/to/obj') example = dbus.Interface(example_remote, bus_name + '.Iface') example.StringifyVariant(123) print example.GetLastInput() MainLoop().run()
elif prop == 'Connection': self._connection = dbus.ObjectPath(value) else: raise ValueError('Read-only or nonexistent property') props[prop] = self._account_props()[prop] self.AccountPropertyChanged(props) elif iface == ACCOUNT_IFACE_AVATAR_IFACE: if prop == 'Avatar': self._avatar = dbus.Struct( (dbus.ByteArray(value[0]), unicode(value[1])), signature='ays') self.AvatarChanged() else: raise ValueError('Nonexistent property') else: raise ValueError('No such interface') if __name__ == '__main__': DBusGMainLoop(set_as_default=True) try: am = AccountManager() except dbus.NameExistsException: print >> sys.stderr, 'AccountManager already running' sys.exit(1) print "AccountManager running..." mainloop = MainLoop() mainloop.run()
self._connection = dbus.ObjectPath(value) else: raise ValueError('Read-only or nonexistent property') props[prop] = self._account_props()[prop] self.AccountPropertyChanged(props) elif iface == ACCOUNT_IFACE_AVATAR_IFACE: if prop == 'Avatar': self._avatar = dbus.Struct( (dbus.ByteArray(value[0]), unicode(value[1])), signature='ays') self.AvatarChanged() else: raise ValueError('Nonexistent property') else: raise ValueError('No such interface') if __name__ == '__main__': DBusGMainLoop(set_as_default=True) try: am = AccountManager() except dbus.NameExistsException: print >> sys.stderr, 'AccountManager already running' sys.exit(1) print "AccountManager running..." mainloop = MainLoop() mainloop.run()
from clipboardms.server import ClipboardMediaServer from dbus.mainloop.glib import DBusGMainLoop from gobject import MainLoop DBusGMainLoop(set_as_default=True) server = ClipboardMediaServer() loop = MainLoop() loop.run()
def run(): global bus global dbusName global myDbusServices global myDbusGroupServices global settings global pathSettings global fileSettings global fileSettingChanges global newFileSettings global sysSettingsDir global groups global busName global tracingEnabled global pathTraces global traceToConsole global traceToFile global traceFileName global traceDebugOn global myDbusMainGroupService global logger DBusGMainLoop(set_as_default=True) # set the settings path fileSettings = pathSettings + fileSettings fileSettingChanges = pathSettings + fileSettingChanges newFileSettings = pathSettings + newFileSettings # setup debug traces. logger = logging.getLogger('localsettings victron applicaiton') #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') formatter = logging.Formatter('%(levelname)s - %(message)s') logger.setLevel(logging.INFO) if traceDebugOn == 1: logger.setLevel(logging.DEBUG) if traceToConsole == 1: print ("log console activated") ch = logging.StreamHandler() ch.setFormatter(formatter) ch.setLevel(logging.DEBUG) logger.addHandler(ch) if traceToFile == 1 : fh = logging.FileHandler('trace.log') fh.setFormatter(formatter) fh.setLevel(logging.DEBUG) print ("tracefilename:") print (traceFileName + traceFileName) logger.addHandler(fh) #tracing.setupTraces(tracingEnabled, pathTraces, traceFileName, traceToConsole, traceToFile, traceDebugOn) logger.debug('tracingPath = %s' % pathTraces) # Print the logscript version logger.info('Localsettings version is: 0x%04x' % version) logger.info('Localsettings PID is: %d' % getpid()) # Trace the python version. pythonVersion = platform.python_version() logger.debug('Current python version: %s' % pythonVersion) # setup signal handling. signal.signal(signal.SIGHUP, handlerSignals) # 1: Hangup detected signal.signal(signal.SIGINT, handlerSignals) # 2: Ctrl-C signal.signal(signal.SIGUSR1, handlerSignals) # 10: kill -USR1 <logscript-pid> signal.signal(signal.SIGTERM, handlerSignals) # 15: Terminate # load system default settings loadSettingsDir(sysSettingsDir, settings) if not path.isdir(pathSettings): print('Error path %s does not exist!' % pathSettings) sys.exit(errno.ENOENT) if path.isfile(newFileSettings): logger.info('New settings file exist') try: tree = etree.parse(newFileSettings) root = tree.getroot() logger.info('New settings file %s validated' % newFileSettings) rename(newFileSettings, fileSettings) logger.info('renamed new settings file to settings file') except: logger.error('New settings file %s invalid' % newFileSettings) remove(newFileSettings) logger.error('%s removed' % newFileSettings) if path.isfile(fileSettings): # Try to validate the settings file. try: tree = etree.parse(fileSettings) root = tree.getroot() migrate_can_profile(tree) logger.info('Settings file %s validated' % fileSettings) except: logger.error('Settings file %s invalid' % fileSettings) remove(fileSettings) logger.error('%s removed' % fileSettings) # check if settings file is present, if not exit create a "empty" settings file. if not path.isfile(fileSettings): logger.warning('Settings file %s not found' % fileSettings) root = etree.Element(settingsRootName) root.set(settingsTag, settingsVersion) tree = etree.ElementTree(root) tree.write(fileSettings, encoding = settingsEncoding, pretty_print = True, xml_declaration = True) logger.warning('Created settings file %s' % fileSettings) # read the settings.xml parseXmlFileToDictonary(fileSettings, settings, groups, None) logger.debug('settings:') logger.debug(settings.items()) logger.debug('groups:') logger.debug(groups) # check if new settings must be changed if path.isfile(fileSettingChanges): # process the settings which must be deleted. delSettings = {} parseXmlFileToDictonary(fileSettingChanges, delSettings, None, "/Change/Delete") logger.debug('setting to delete:') logger.debug(delSettings.items()) for item in delSettings: if item in settings: logger.debug('delete item %s' % item) del settings[item] saveChanges = True # process the settings which must be added. addSettings = {} parseXmlFileToDictonary(fileSettingChanges, addSettings, None, "/Change/Add") logger.debug('setting to add:') logger.debug(addSettings.items()) saveChanges = False for item in addSettings: if not item in settings: logger.debug('add item %s' % item) settings[item] = addSettings[item] saveChanges = True if saveChanges == True: logger.warning('Change settings according to %s' % fileSettingChanges) parseDictonaryToXmlFile(settings, fileSettings) # update settings and groups from file. settings = {} groups = [] parseXmlFileToDictonary(fileSettings, settings, groups, None) logger.debug('settings:') logger.debug(settings.items()) logger.debug('groups:') logger.debug(groups) remove(fileSettingChanges) # For a PC, connect to the SessionBus # For a CCGX, connect to the SystemBus bus = dbus.SessionBus() if 'DBUS_SESSION_BUS_ADDRESS' in environ else dbus.SystemBus() busName = dbus.service.BusName(dbusName, bus) root = RootObject(busName) for setting in settings: myDbusObject = MyDbusObject(busName, setting) myDbusServices.append(myDbusObject) for group in groups: myDbusObject = MyDbusObject(busName, group) myDbusGroupServices.append(myDbusObject) myDbusMainGroupService = myDbusGroupServices[0] MainLoop().run()
def export_share( self, share ): serviceName = "%s:%s" % ( self.hostname, share ) serviceTXT = "%s%s" % ( serviceTXTPrefix, share ) self.group.AddService( IF_UNSPEC, PROTO_INET, UInt32( 0 ), serviceName, serviceType, serviceDomain, self.hostname, UInt16( servicePort ), string_array_to_txt_array( [serviceTXT] ) ) # We are a Script, lets go! if __name__ == '__main__': # prepare publish avahi = NfsAvahiPublish() avahi.export() # Start the MainLoop for Avahi main_loop = MainLoop() main_loop.run()#!/usr/bin/python # -*- coding: utf-8 -*- # # nfsmount-exporter.py Version 0.2 # # Copyright 2008 Mario Bielert <*****@*****.**> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the