Пример #1
0
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)
Пример #2
0
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()
    def run(self):
        """
		Attach server and run the loop (see :attr:`loop`).
		"""
        if self.server.attach():
            self.loop = MainLoop()
            self.loop.run()
Пример #4
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")
Пример #6
0
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()
Пример #7
0
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()
Пример #8
0
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("")
Пример #9
0
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)
Пример #10
0
    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
Пример #11
0
    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()
Пример #12
0
    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+')
Пример #13
0
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)
Пример #14
0
                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()
Пример #15
0
# 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()
Пример #16
0
def dbus_loop(actor):
    threads_init()
    mainloop = MainLoop()
    actor.set_event_loop(mainloop)
    actor.start()
    mainloop.run()
Пример #17
0
 def listen(self):
     from gobject import MainLoop
     loop = MainLoop()
     loop.run()
Пример #18
0
def main():
    __start()
    from gobject import MainLoop
    MainLoop().run()
    return
Пример #19
0
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()