def run(self): DBusGMainLoop(set_as_default=True) part_mgr = PartMgrService()
def __init__(self): DBusGMainLoop(set_as_default=True) DBusRunner.__bus = dbus.SystemBus()
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop dbus_loop = DBusGMainLoop(set_as_default=True) ml = glib.MainLoop() bus = dbus.SystemBus( ) #org.bluez deamon is on system bus. Hence create object of class SystemBus manager = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.bluez.Manager') print manager.ListAdapters() # print all adapter print manager.DefaultAdapter() # print default adapter def_interface = dbus.Interface( bus.get_object('org.bluez', manager.DefaultAdapter()), 'org.bluez.Adapter') print def_interface.GetProperties() # print properties of default interface ### The below function will be called whenever DeviceFound Signal will be emmited ## def device_found(addr, value): print 'Found:', addr print "Descriptor:", value if value == 'mr. singh': # Name of our target BT device temp = def_interface.CreatePairedDevice(addr, manager.DefaultAdapter(), "NoInputNoOutput") print temp def_interface.StopDiscovery() ml.quit()
def main(): _create_dirs() """ Main function that starts everything """ if is_wayland( ) and gdk_backend().lower() != 'x11' and not is_wayland_compatibility_on(): warn = """ [!] Looks like you are in Wayland session Please run Ulauncher with env var GDK_BACKEND set to 'x11' like this: GDK_BACKEND=x11 ulauncher """ print(warn, file=sys.stderr) sys.exit(1) # start DBus loop DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() instance = bus.request_name(DBUS_SERVICE) if instance != dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER: toggle_window = dbus.SessionBus().get_object( DBUS_SERVICE, DBUS_PATH).get_dbus_method("toggle_window") toggle_window() # return options = get_options() # setup_logging(options) logger = logging.getLogger('everylauncher') logger.info('EveryLauncher version %s' % get_version()) logger.info("Is Wayland: %s" % is_wayland()) logger.info("Wayland compatibility: %s" % ('on' if is_wayland_compatibility_on() else 'off')) # log uncaught exceptions # def except_hook(exctype, value, tb): # logger.error("Uncaught exception", exc_info=(exctype, value, tb)) # sys.excepthook = except_hook app = QApplication(sys.argv) app.setQuitOnLastWindowClosed(False) QApplication.setOrganizationName(ORGANIZATION_NAME) QApplication.setOrganizationDomain(ORGANIZATION_DOMAIN) QApplication.setApplicationName(APPLICATION_NAME) # engine = QQmlApplicationEngine() view = myQuickWidget() view.setWindowFlags(Qt.WindowStaysOnTopHint) view.setWindowFlags(QtCore.Qt.WindowCloseButtonHint \ | QtCore.Qt.FramelessWindowHint) # view.setWindowTitle(QObject.tr("EveryLauncher")) # TODO hide when lise focus view.move((QApplication.desktop().width() - view.width()) / 2, QApplication.desktop().height() / 1.7 - view.height()) engine = view.engine() model = recollQueryModel(RECOLL_CONFIG_DIR, []) proxy = QSortFilterProxyModel() proxy.setSourceModel(model) proxy.setFilterRole(recollQueryModel.Role_TYPE) # qmlRegisterType(recollQueryModel, 'RecollQuery', 1, 0, 'EveryQueryModel') tray = SystemTray.get_instance(view) desktop_servers = QDesktopServices() engine.rootContext().setContextProperty("queryModel", model) engine.rootContext().setContextProperty("filterModel", proxy) engine.rootContext().setContextProperty("systemTray", tray) engine.rootContext().setContextProperty("desktopServices", desktop_servers) EveryLauncherDbusService(tray) if not options.hide_window: tray.showMainWindow(True) # engine.load(QUrl("ui/QML/main.qml")) # if not engine.rootObjects(): # sys.exit(-1) dir = os.path.dirname(os.path.abspath(__file__)) view.setSource(QUrl(os.path.join(dir, "ui/QML/main.qml"))) setting = QSettings() setting.beginGroup("General") if trans_to_bool(setting.value(SHOW_INDICATOR, True)): tray.show() if trans_to_bool(setting.value(SHOW_WINDOW_ON_START, True)): view.show() setting.endGroup() # w=PreferenceWindow() # w.show() # tray.show() # if Settings.get_instance().get_property('show-indicator-icon'): # workaround to make Ctrl+C quiting the app # signal_handler = SignalHandler(window) # TODO add shortkey in deepin control sys.exit(app.exec_())
def main(): check_autostart() check_database() (options, parser) = parse_options(get_version()) set_up_logging("remindor_qt", log_file(), config_dir(), options, get_version()) import logging logger = logging.getLogger('remindor_qt') #Run the application. app = QApplication([""]) app.setWindowIcon(QIcon.fromTheme("remindor-qt")) app.setApplicationName("Remindor-Qt") app.setApplicationVersion(get_version()) app.setOrganizationDomain("http://bhdouglass.com/remindor/") app.setQuitOnLastWindowClosed(False) if os.name == 'nt': for plugins_dir in [ os.path.join(p, 'plugins') for p in PySide.__path__ ]: qApp.addLibraryPath(plugins_dir) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8")) if use_dbus: DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus() ds = dbus_service(session_bus) if options.add: dialog = ReminderDialog(None) dialog.exec_() ds.emitUpdate() sys.exit(0) elif options.quick: dialog = QuickDialog(None) dialog.exec_() ds.emitUpdate() sys.exit(0) elif options.simple: dialog = SimpleDialog(None) dialog.exec_() ds.emitUpdate() sys.exit(0) elif options.manage: ds.emitManage() sys.exit(0) elif options.prefs: dialog = PreferencesDialog(None) dialog.exec_() ds.emitUpdate() sys.exit(0) elif options.stop: ds.emitStop() sys.exit(0) elif options.update: ds.emitUpdate() sys.exit(0) elif options.close: ds.emitClose() sys.exit(0) else: window = RemindorQtWindow.RemindorQtWindow(ds) bus = dbus.SystemBus() bus.add_signal_receiver(window.update_schedule, signal_name='Resuming', dbus_interface='org.freedesktop.UPower', path='/org/freedesktop/UPower') bus2 = dbus.SessionBus() bus2.add_signal_receiver(window.dbus_receiver, signal_name=None, dbus_interface=ds.interface(), path=ds.path()) else: logger.debug( 'Unable to initialize dbus, this features will be disabled') if options.add or options.quick or options.manage or options.prefs or options.stop or options.update or options.close: logger.warn( 'dbus is not available, command line options are disabled') print 'dbus is not available, command line options are disabled' sys.exit(0) else: window = RemindorQtWindow.RemindorQtWindow() app.exec_()
try: # dbus essentials from dbus import SessionBus from dbus import Interface from dbus import Byte from dbus import ByteArray # # now we try to determine which mainloop(s) we can access # # glib try: from dbus.mainloop.glib import DBusGMainLoop LOOP_GLIB = DBusGMainLoop() except ImportError: # No problem pass # qt try: from dbus.mainloop.qt import DBusQtMainLoop LOOP_QT = DBusQtMainLoop(set_as_default=True) except ImportError: # No problem pass # We're good as long as at least one
:copyright: 2005-2008 by The PIDA Project :license: GPL 2 or later (see README/COPYING/LICENSE) """ import os from pango import Font from pygtkhelpers.gthreads import gcall from pida.core.environment import workspace_name try: import dbus from dbus.lowlevel import SignalMessage from dbus.mainloop.glib import DBusGMainLoop DBusMainloop = DBusGMainLoop(set_as_default=True) from dbus.service import (Object, INTROSPECTABLE_IFACE, _method_reply_error, _method_reply_return) from dbus.service import method, signal from dbus import Signature import _dbus_bindings # Is dbus available? # Throws dbus.exceptions.DBusException if not. #XXX: try: BUS_NAME = dbus.service.BusName( 'uk.co.pida.pida.p%s' % os.getpid(), bus=dbus.SessionBus()) has_dbus = True
def __init__(self): DBusGMainLoop(set_as_default=True) self._system_bus, self._dbus_manager = \ DbusServiceHandler._get_systemd_interface()
def setup_dbus(): DBusGMainLoop(set_as_default=True) system_bus = dbus.SystemBus() name = dbus.service.BusName(DBUS_SERVICE, bus=system_bus) return name
def handle_system_suspend(): DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_signal_receiver(handle_suspend_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager', 'org.freedesktop.login1')
def initialize(self): super(desktopui_ScreenLocker, self).initialize() DBusGMainLoop(set_as_default=True) self.player = input_playback.InputPlayback() self.player.emulate(input_type='keyboard') self.player.find_connected_inputs()
def setup_for_cli_run(): import signal from dbus.mainloop.glib import DBusGMainLoop, threads_init threads_init() DBusGMainLoop(set_as_default=True) signal.signal(signal.SIGINT, signal.SIG_DFL) # quit on Ctrl-C
def __init__(self, host): self._client = XBMCClient('XBMCPidgin', ip=host) self._client.connect() DBusGMainLoop(set_as_default=True) self._bus = dbus.SessionBus()
def __init__(self): print("Initializing nautilus-font-manager extension") DBusGMainLoop(set_as_default=True) self.bus = dbus.SessionBus() self.bus.watch_name_owner('org.gnome.FontViewer', FontViewer.set_state)
def do_activate (self): DBusGMainLoop (set_as_default = True) name = dbus.service.BusName ('org.mpris.MediaPlayer2.totem', bus = dbus.SessionBus ()) self.root = Root (name, self.object)
#def system_resumed(*args): # alert("System resumed") # run_prey() ####################### # main ####################### if __name__ == '__main__': # log("Initializing") run_at = None # Setup message bus. bus = dbus.SystemBus(mainloop=DBusGMainLoop()) # Connect to StateChanged signal from NetworkManager try: nm = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') nm_interface = dbus.Interface(nm, 'org.freedesktop.NetworkManager') nm_interface.connect_to_signal('StateChanged', network_state_changed) except dbus.exceptions.DBusException: print "NetworkManager DBus interface not found! Please make sure NM is installed." sys.exit(1) if connected(): run_prey() # upower = bus.get_object('org.freedesktop.UPower', '/org/freedesktop/UPower')
def __init__(self, name, service_type='_ros-master._tcp', host=socket.gethostname(), port=11311, domain='local', txt_array=[]): '''.......................................................................... Initialization method of the Zeroconf class. @param name: the name of the local ROS master @type name: C{str} @param service_type: the avahi service type @type service_type: C{str} @param host: the host of the local ROS master @type host: C{str} @param port: the port of the local ROS master @type port: C{int} @param domain: the domain name @type domain: C{str} @param txt_array: (optional) additional information @type txt_array: C{[str]} ..........................................................................''' self.masterInfo = MasterInfo(name, service_type, domain, host, port, txt_array) # FIXME Review thread locking as needed. # init thread threading.Thread.__init__(self) self._lock = threading.RLock() # Gobjects are an event based model of evil, do not trust them, DBusGMainLoop(set_as_default=True) # Magic? Yes, don't start threads without it. # Why? I'm sure thats documented somewhere. gobject.threads_init() dbus.mainloop.glib.threads_init() self.__main_loop = gobject.MainLoop() self.__bus = dbus.SystemBus() # Initialize iterface to DBUS Server self.__server = dbus.Interface( self.__bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) # The DBUS entry group self.__group = None # Monitor server state changes self.__server.connect_to_signal("StateChanged", self.__avahi_callback_state_changed) # the browser to register the updates and new services self.__browser = dbus.Interface( self.__bus.get_object( avahi.DBUS_NAME, self.__server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, self.masterInfo.stype, self.masterInfo.domain, dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER) self.__browser.connect_to_signal( "ItemNew", self.__avahi_callback_service_browser_new) self.__browser.connect_to_signal( "ItemRemove", self.__avahi_callback_service_browser_remove)
def main(): parser = argparse.ArgumentParser( prog='system-image-cli', description='Ubuntu System Image Upgrader') parser.add_argument('--version', action='version', version='system-image-cli {}'.format(__version__)) parser.add_argument('-C', '--config', default=DEFAULT_CONFIG_D, action='store', metavar='DIRECTORY', help="""Use the given configuration directory instead of the default""") parser.add_argument('-b', '--build', default=None, action='store', help="""Override the current build number just this once""") parser.add_argument('-c', '--channel', default=None, action='store', help="""Override the channel just this once. Use in combination with `--build 0` to switch channels.""") parser.add_argument('-d', '--device', default=None, action='store', help='Override the device name just this once') parser.add_argument('-f', '--filter', default=None, action='store', help="""Filter the candidate paths to contain only full updates or only delta updates. The argument to this option must be either `full` or `delta`""") parser.add_argument('-m', '--maximage', default=None, type=int, help="""After the winning upgrade path is selected, remove all images with version numbers greater than the given one. If no images remain in the winning path, the device is considered up-to-date.""") parser.add_argument('-g', '--no-apply', default=False, action='store_true', help="""Download (i.e. "get") all the data files and prepare for updating, but don't actually reboot the device into recovery to apply the update""") parser.add_argument('-i', '--info', default=False, action='store_true', help="""Show some information about the current device, including the current build number, device name and channel, then exit""") parser.add_argument('-n', '--dry-run', default=False, action='store_true', help="""Calculate and print the upgrade path, but do not download or apply it""") parser.add_argument('-v', '--verbose', default=0, action='count', help='Increase verbosity') parser.add_argument('--progress', default=[], action='append', help="""Add a progress meter. Available meters are: dots, logfile, and json. Multiple --progress options are allowed.""") parser.add_argument('-p', '--percentage', default=None, action='store', help="""Override the device's phased percentage value during upgrade candidate calculation.""") parser.add_argument('--list-channels', default=False, action='store_true', help="""List all available channels, then exit""") parser.add_argument('--factory-reset', default=False, action='store_true', help="""Perform a destructive factory reset and reboot. WARNING: this will wipe all user data on the device!""") parser.add_argument('--production-reset', default=False, action='store_true', help="""Perform a destructive production reset (similar to factory reset) and reboot. WARNING: this will wipe all user data on the device!""") parser.add_argument('--switch', default=None, action='store', metavar='CHANNEL', help="""Switch to the given channel. This is equivalent to `-c CHANNEL -b 0`.""") # Settings options. parser.add_argument('--show-settings', default=False, action='store_true', help="""Show all settings as key=value pairs, then exit""") parser.add_argument('--set', default=[], action='append', metavar='KEY=VAL', help="""Set a key and value in the settings, adding the key if it doesn't yet exist, or overriding its value if the key already exists. Multiple --set arguments can be given.""") parser.add_argument('--get', default=[], action='append', metavar='KEY', help="""Get the value for a key. If the key does not exist, a default value is returned. Multiple --get arguments can be given.""") parser.add_argument('--del', default=[], action='append', metavar='KEY', dest='delete', help="""Delete the key and its value. It is a no-op if the key does not exist. Multiple --del arguments can be given.""") parser.add_argument('--override-gsm', default=False, action='store_true', help="""When the device is set to only download over WiFi, but is currently on GSM, use this switch to temporarily override the update restriction. This switch has no effect when using the cURL based downloader.""") # Hidden system-image-cli only feature for testing purposes. LP: #1333414 parser.add_argument('--skip-gpg-verification', default=False, action='store_true', help=argparse.SUPPRESS) args = parser.parse_args(sys.argv[1:]) try: config.load(args.config) except (TypeError, FileNotFoundError): parser.error('\nConfiguration directory not found: {}'.format( args.config)) assert 'parser.error() does not return' # pragma: no cover if args.skip_gpg_verification: print("""\ WARNING: All GPG signature verifications have been disabled. Your upgrades are INSECURE.""", file=sys.stderr) config.skip_gpg_verification = True config.override_gsm = args.override_gsm # Perform factory and production resets. if args.factory_reset: factory_reset() # We should never get here, except possibly during the testing # process, so just return as normal. return 0 if args.production_reset: production_reset() # We should never get here, except possibly during the testing # process, so just return as normal. return 0 # Handle all settings arguments. They are mutually exclusive. if sum( bool(arg) for arg in (args.set, args.get, args.delete, args.show_settings)) > 1: parser.error('Cannot mix and match settings arguments') assert 'parser.error() does not return' # pragma: no cover if args.show_settings: rows = sorted(Settings()) for row in rows: print('{}={}'.format(*row)) return 0 if args.get: settings = Settings() for key in args.get: print(settings.get(key)) return 0 if args.set: settings = Settings() for keyval in args.set: key, val = keyval.split('=', 1) settings.set(key, val) return 0 if args.delete: settings = Settings() for key in args.delete: settings.delete(key) return 0 # Sanity check -f/--filter. if args.filter is None: candidate_filter = None elif args.filter == 'full': candidate_filter = full_filter elif args.filter == 'delta': candidate_filter = delta_filter else: parser.error('Bad filter type: {}'.format(args.filter)) assert 'parser.error() does not return' # pragma: no cover # Create the temporary directory if it doesn't exist. makedirs(config.system.tempdir) # Initialize the loggers. initialize(verbosity=args.verbose) log = logging.getLogger('systemimage') # We assume the cache_partition already exists, as does the /etc directory # (i.e. where the archive master key lives). # Command line overrides. Process --switch first since if both it and # -c/-b are given, the latter take precedence. if args.switch is not None: config.build_number = 0 config.channel = args.switch if args.build is not None: try: config.build_number = int(args.build) except ValueError: parser.error('-b/--build requires an integer: {}'.format( args.build)) assert 'parser.error() does not return' # pragma: no cover if args.channel is not None: config.channel = args.channel if args.device is not None: config.device = args.device if args.percentage is not None: config.phase_override = args.percentage if args.info: alias = getattr(config.service, 'channel_target', None) kws = dict( build_number=config.build_number, device=config.device, channel=config.channel, last_update=last_update_date(), ) if alias is None: template = """\ current build number: {build_number} device name: {device} channel: {channel} last update: {last_update}""" else: template = """\ current build number: {build_number} device name: {device} channel: {channel} alias: {alias} last update: {last_update}""" kws['alias'] = alias print(dedent(template).format(**kws)) # If there's additional version details, print this out now too. We # sort the keys in reverse order because we want 'ubuntu' to generally # come first. details = version_detail() for key in sorted(details, reverse=True): print('version {}: {}'.format(key, details[key])) return 0 DBusGMainLoop(set_as_default=True) if args.list_channels: state = State() try: state.run_thru('get_channel') except Exception: print( 'Exception occurred during channel search; ' 'see log file for details', file=sys.stderr) log.exception('system-image-cli exception') return 1 print('Available channels:') for key in sorted(state.channels): alias = state.channels[key].get('alias') if alias is None: print(' {}'.format(key)) else: print(' {} (alias for: {})'.format(key, alias)) return 0 state = State() state.candidate_filter = candidate_filter if args.maximage is not None: state.winner_filter = version_filter(args.maximage) for meter in args.progress: if meter == 'dots': state.downloader.callbacks.append(_DotsProgress().callback) elif meter == 'json': state.downloader.callbacks.append(_json_progress) elif meter == 'logfile': state.downloader.callbacks.append(_LogfileProgress(log).callback) else: parser.error('Unknown progress meter: {}'.format(meter)) assert 'parser.error() does not return' # pragma: no cover if args.dry_run: try: state.run_until('download_files') except Exception: print( 'Exception occurred during dry-run; ' 'see log file for details', file=sys.stderr) log.exception('system-image-cli exception') return 1 # Say -c <no-such-channel> was given. This will fail. if state.winner is None or len(state.winner) == 0: print('Already up-to-date') else: winning_path = [str(image.version) for image in state.winner] kws = dict(path=COLON.join(winning_path)) target_build = state.winner[-1].version if state.channel_switch is None: # We're not switching channels due to an alias change. template = 'Upgrade path is {path}' percentage = phased_percentage(config.channel, target_build) else: # This upgrade changes the channel that our alias is mapped # to, so include that information in the output. template = 'Upgrade path is {path} ({from} -> {to})' kws['from'], kws['to'] = state.channel_switch percentage = phased_percentage(kws['to'], target_build) print(template.format(**kws)) print('Target phase: {}%'.format(percentage)) return 0 else: # Run the state machine to conclusion. Suppress all exceptions, but # note that the state machine will log them. If an exception occurs, # exit with a non-zero status. log.info('running state machine [{}/{}]', config.channel, config.device) try: if args.no_apply: state.run_until('apply') else: list(state) except KeyboardInterrupt: # pragma: no cover return 0 except Exception as error: print('Exception occurred during update; see log file for details', file=sys.stderr) log.exception('system-image-cli exception') # This is a little bit of a hack because it's not generalized to # all values of --progress. But OTOH, we always want to log the # error, so --progress=logfile is redundant, and --progress=dots # doesn't make much sense either. Just just include some JSON # output if --progress=json was specified. if 'json' in args.progress: print(json.dumps(dict(type='error', msg=str(error)))) return 1 else: return 0 finally: log.info('state machine finished')
def show(text): threading.Thread(target=tshow, args=[text]).start() def sysnotifications(bus, message): args = message.get_args_list() # print([arg for arg in args]) try: if message.get_member() == "PropertiesChanged" and args[0] == "org.bluez.MediaTransport1" and \ "State" in args[1] and args[1]["State"] == "active": # Is Bluetooth transport message show("BT Media Connected") except: print(str(sys.exc_info())) sysbus = dbus.SystemBus(mainloop=DBusGMainLoop(set_as_default=True)) sysbus.add_match_string_non_blocking( "eavesdrop=true, interface='org.freedesktop.DBus.Properties', " "member='PropertiesChanged'") sysbus.add_message_filter(sysnotifications) try: mainloop = GLib.MainLoop() mainloop.run() except KeyboardInterrupt: print("Keyboard interrupt")
def initialize(self): super(platform_SessionManagerBlockDevmodeSetting, self).initialize() ownership.restart_ui_to_clear_ownership_files() self._bus_loop = DBusGMainLoop(set_as_default=True)
def setup_mainloop(): global loop_ loop_ = DBusGMainLoop(set_as_default=True)
def main(): parser = argparse.ArgumentParser( description='Publishes values from the D-Bus to an MQTT broker') parser.add_argument('-d', '--debug', help='set logging level to debug', action='store_true') parser.add_argument('-q', '--mqtt-server', nargs='?', default=None, help='name of the mqtt server') parser.add_argument('-u', '--mqtt-user', default=None, help='mqtt user name') parser.add_argument('-P', '--mqtt-password', default=None, help='mqtt password') parser.add_argument( '-c', '--mqtt-certificate', default=None, help='path to CA certificate used for SSL communication') parser.add_argument('-b', '--dbus', default=None, help='dbus address') parser.add_argument('-k', '--keep-alive', default=60, help='keep alive interval in seconds', type=int) parser.add_argument( '-i', '--init-broker', action='store_true', help='Tries to setup communication with VRM MQTT broker') args = parser.parse_args() print("-------- dbus_mqtt, v{} is starting up --------".format( SoftwareVersion)) logger = setup_logging(args.debug) # This allows us to use gobject code in new threads gobject.threads_init() mainloop = gobject.MainLoop() # Have a mainloop, so we can send/receive asynchronous calls to and from dbus DBusGMainLoop(set_as_default=True) keep_alive_interval = args.keep_alive if args.keep_alive > 0 else None handler = DbusMqtt(mqtt_server=args.mqtt_server, ca_cert=args.mqtt_certificate, user=args.mqtt_user, passwd=args.mqtt_password, dbus_address=args.dbus, keep_alive_interval=keep_alive_interval, init_broker=args.init_broker) # Start and run the mainloop try: mainloop.run() except KeyboardInterrupt: pass
def DBusMainLoop(cls): from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True)
def main(): global args parser = argparse.ArgumentParser() exclusive_group = parser.add_mutually_exclusive_group() exclusive_group.add_argument('--debug', action='store_true', help='add some debug info and additional checks') exclusive_group.add_argument( '--monitor', metavar='update_rate', const=1.0, type=float, nargs='?', help='realtime monitoring of throttling causes (default 1s)', ) parser.add_argument('--config', default='/etc/lenovo_fix.conf', help='override default config file path') parser.add_argument('--force', action='store_true', help='bypass compatibility checks (EXPERTS only)') args = parser.parse_args() if not args.force: check_kernel() check_cpu() print('[I] Loading config file.') config = load_config() power['source'] = 'BATTERY' if is_on_battery(config) else 'AC' platform_info = get_cpu_platform_info() if args.debug: for key, value in platform_info.items(): print('[D] cpu platform info: {} = {}'.format(key.replace("_", " "), value)) regs = calc_reg_values(platform_info, config) if not config.getboolean('GENERAL', 'Enabled'): return exit_event = Event() thread = Thread(target=power_thread, args=(config, regs, exit_event)) thread.daemon = True thread.start() undervolt(config) set_icc_max(config) # handle dbus events for applying undervolt/IccMax on resume from sleep/hybernate def handle_sleep_callback(sleeping): if not sleeping: undervolt(config) set_icc_max(config) def handle_ac_callback(*args): try: power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC' power['method'] = 'dbus' except: power['method'] = 'polling' DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() # add dbus receiver only if undervolt/IccMax is enabled in config if any( config.getfloat(key, plane, fallback=0) != 0 for plane in VOLTAGE_PLANES for key in UNDERVOLT_KEYS + ICCMAX_KEYS ): bus.add_signal_receiver( handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager', 'org.freedesktop.login1' ) bus.add_signal_receiver( handle_ac_callback, signal_name="PropertiesChanged", dbus_interface="org.freedesktop.DBus.Properties", path="/org/freedesktop/UPower/devices/line_power_AC", ) print('[I] Starting main loop.') if args.monitor is not None: monitor_thread = Thread(target=monitor, args=(exit_event, args.monitor)) monitor_thread.daemon = True monitor_thread.start() try: loop = GLib.MainLoop() loop.run() except (KeyboardInterrupt, SystemExit): pass exit_event.set() loop.quit() thread.join(timeout=1) if args.monitor is not None: monitor_thread.join(timeout=0.1)
def do_startup(self): Gtk.Application.do_startup(self) self.create_actions() builder = Gtk.Builder() builder.set_translation_domain(gpodder.textdomain) menu_filename = None for ui_folder in gpodder.ui_folders: filename = os.path.join(ui_folder, 'gtk/menus.ui') if os.path.exists(filename): builder.add_from_file(filename) menu_filename = filename break menubar = builder.get_object('menubar') if menubar is None: logger.error('Cannot find gtk/menus.ui in %r, exiting' % gpodder.ui_folders) sys.exit(1) self.menu_view_columns = builder.get_object('menuViewColumns') self.set_menubar(menubar) # If $XDG_CURRENT_DESKTOP is set then it contains a colon-separated list of strings. # https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html # See https://askubuntu.com/a/227669 for a list of values in different environments xdg_current_desktops = os.environ.get('XDG_CURRENT_DESKTOP', '').split(':') # See https://developer.gnome.org/gtk3/stable/gtk-running.html # GTK_CSD=0 is used to disable client side decorations csd_disabled = os.environ.get('GTK_CSD') == '0' self.want_headerbar = ('GNOME' in xdg_current_desktops ) and not gpodder.ui.osx and not csd_disabled self.app_menu = builder.get_object('app-menu') if self.want_headerbar: # Use GtkHeaderBar for client-side decorations on recent GNOME 3 versions self.header_bar_menu_button = Gtk.Button.new_from_icon_name( 'open-menu-symbolic', Gtk.IconSize.SMALL_TOOLBAR) self.header_bar_menu_button.set_action_name('app.menu') self.header_bar_refresh_button = Gtk.Button.new_from_icon_name( 'view-refresh-symbolic', Gtk.IconSize.SMALL_TOOLBAR) self.header_bar_refresh_button.set_action_name('win.updateChannel') self.menu_popover = Gtk.Popover.new_from_model( self.header_bar_menu_button, self.app_menu) self.menu_popover.set_position(Gtk.PositionType.BOTTOM) for (accel, action) in parse_app_menu_for_accels(menu_filename): self.add_accelerator(accel, action, None) else: self.set_app_menu(self.app_menu) Gtk.Window.set_default_icon_name('gpodder') try: dbus_main_loop = DBusGMainLoop(set_as_default=True) gpodder.dbus_session_bus = dbus.SessionBus(dbus_main_loop) self.bus_name = dbus.service.BusName(gpodder.dbus_bus_name, bus=gpodder.dbus_session_bus) except dbus.exceptions.DBusException as dbe: logger.warn('Cannot get "on the bus".', exc_info=True) dlg = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, _('Cannot start gPodder')) dlg.format_secondary_markup(_('D-Bus error: %s') % (str(dbe), )) dlg.set_title('gPodder') dlg.run() dlg.destroy() sys.exit(0) util.idle_add(self.check_root_folder_path_gui)
def test_connman(default_config): DBusGMainLoop(set_as_default=True) cm = ConnMan(default_config) assert (1)
else: print( "No session data about %s, no need restore session." % (buf.url)) else: print("No data in session file, no need restore session.") else: print("Not found %s, no need restore session." % (self.session_file_path)) if __name__ == "__main__": import sys import signal DBusGMainLoop(set_as_default=True) # WARING: only use once in one process bus = dbus.SessionBus() if bus.request_name( EAF_DBUS_NAME) != dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER: print("EAF process has startup.") else: emacs_width = emacs_height = 0 app = QApplication(sys.argv) eaf = EAF(sys.argv[1:]) print("EAF process start.") signal.signal(signal.SIGINT, signal.SIG_DFL)
def __init__(self): self.driver_start_time = datetime.now() # data from yaml config file self._cfg = self.get_config_data() _cfg_bms = self._cfg['BMSData'] # TODO: use venus settings to define these values #Initial BMS values eventually read from settings. self._bms_data = BMSData(max_battery_voltage=_cfg_bms['max_battery_voltage'], \ min_battery_voltage=_cfg_bms['min_battery_voltage'], low_battery_voltage=_cfg_bms['low_battery_voltage'], \ charge_bulk_amps=_cfg_bms['charge_bulk_amps'], max_discharge_amps=_cfg_bms['max_discharge_amps'], \ charge_absorb_voltage=_cfg_bms['charge_absorb_voltage'], charge_float_voltage=_cfg_bms['charge_float_voltage'], \ time_min_absorb=_cfg_bms['time_min_absorb'], rebulk_voltage=_cfg_bms['rebulk_voltage']) self.bms_controller = BMSChargeController(charge_bulk_current=self._bms_data.charge_bulk_amps, \ charge_absorb_voltage=self._bms_data.charge_absorb_voltage, charge_float_voltage=self._bms_data.charge_float_voltage, \ time_min_absorb=self._bms_data.time_min_absorb, rebulk_voltage=self._bms_data.rebulk_voltage) ret = self.bms_controller.start_charging() # Have a mainloop, so we can send/receive asynchronous calls to and from dbus DBusGMainLoop(set_as_default=True) self._can_bus = False self._safety_off = False #flag to see if we every shut the inverters off due to low batt. logger.debug("Can bus init") try: self._can_bus = can.interface.Bus(bustype=canBusType, channel=canBusChannel, bitrate=500000) except can.CanError as e: logger.error(e) logger.debug("Can bus init done") # Add the AcInput1 setting if it doesn't exist so that the grid data is reported # to the system by dbus-systemcalc-py service settings = SettingsDevice( bus=dbus.SystemBus( ), # if (platform.machine() == 'armv7l') else dbus.SessionBus(), supportedSettings={ 'acinput': ['/Settings/SystemSetup/AcInput1', 1, 0, 0], 'hub4mode': ['/Settings/CGwacs/Hub4Mode', 3, 0, 0], 'gridmeter': ['/Settings/CGwacs/RunWithoutGridMeter', 1, 0, 0], 'acsetpoint': ['/Settings/CGwacs/AcPowerSetPoint', 0, 0, 0], 'maxchargepwr': ['/Settings/CGwacs/MaxChargePower', 0, 0, 0], 'maxdischargepwr': ['/Settings/CGwacs/MaxDischargePower', 0, 0, 0], 'maxchargepercent': ['/Settings/CGwacs/MaxChargePercentage', 0, 0, 0], 'maxdischargepercent': ['/Settings/CGwacs/MaxDischargePercentage', 0, 0, 0], 'essMode': ['/Settings/CGwacs/BatteryLife/State', 0, 0, 0], }, eventCallback=None) # Why this dummy? Because DbusMonitor expects these values to be there, even though we don't # need them. So just add some dummy data. This can go away when DbusMonitor is more generic. dummy = { 'code': None, 'whenToLog': 'configChange', 'accessLevel': None } dbus_tree = {'com.victronenergy.system': {'/Dc/Battery/Soc': dummy, '/Dc/Battery/Current': dummy, '/Dc/Battery/Voltage': dummy, \ '/Dc/Pv/Current': dummy, '/Ac/PvOnOutput/L1/Power': dummy, '/Ac/PvOnOutput/L2/Power': dummy, }} self._dbusmonitor = self._create_dbus_monitor( dbus_tree, valueChangedCallback=self._dbus_value_changed) self._dbusservice = self._create_dbus_service() self._dbusservice.add_path('/Serial', value=12345) # /SystemState/State -> 0: Off # -> 1: Low power # -> 2: VE.Bus Fault condition # -> 3: Bulk charging # -> 4: Absorption charging # -> 5: Float charging # -> 6: Storage mode # -> 7: Equalisation charging # -> 8: Passthru # -> 9: Inverting # -> 10: Assisting # -> 256: Discharging # -> 257: Sustain self._dbusservice.add_path('/State', 0) self._dbusservice.add_path('/Mode', 3) self._dbusservice.add_path('/Ac/PowerMeasurementType', 0) self._dbusservice.add_path('/Hub4/AssistantId', 5) self._dbusservice.add_path('/Hub4/DisableCharge', value=0, writeable=True) self._dbusservice.add_path('/Hub4/DisableFeedIn', value=0, writeable=True) self._dbusservice.add_path('/Hub4/DoNotFeedInOverVoltage', value=0, writeable=True) self._dbusservice.add_path('/Hub4/L1/AcPowerSetpoint', value=0, writeable=True) self._dbusservice.add_path('/Hub4/L2/AcPowerSetpoint', value=0, writeable=True) self._dbusservice.add_path('/Hub4/Sustain', value=0, writeable=True) self._dbusservice.add_path('/Hub4/L1/MaxFeedInPower', value=0, writeable=True) self._dbusservice.add_path('/Hub4/L2/MaxFeedInPower', value=0, writeable=True) # Create the inverter/charger paths self._dbusservice.add_path('/Ac/Out/L1/P', -1) self._dbusservice.add_path('/Ac/Out/L2/P', -1) self._dbusservice.add_path('/Ac/Out/L1/I', -1) self._dbusservice.add_path('/Ac/Out/L2/I', -1) self._dbusservice.add_path('/Ac/Out/L1/V', -1) self._dbusservice.add_path('/Ac/Out/L2/V', -1) self._dbusservice.add_path('/Ac/Out/L1/F', -1) self._dbusservice.add_path('/Ac/Out/L2/F', -1) self._dbusservice.add_path('/Ac/Out/P', -1) self._dbusservice.add_path('/Ac/ActiveIn/L1/P', -1) self._dbusservice.add_path('/Ac/ActiveIn/L2/P', -1) self._dbusservice.add_path('/Ac/ActiveIn/P', -1) self._dbusservice.add_path('/Ac/ActiveIn/L1/V', -1) self._dbusservice.add_path('/Ac/ActiveIn/L2/V', -1) self._dbusservice.add_path('/Ac/ActiveIn/L1/F', -1) self._dbusservice.add_path('/Ac/ActiveIn/L2/F', -1) self._dbusservice.add_path('/Ac/ActiveIn/L1/I', -1) self._dbusservice.add_path('/Ac/ActiveIn/L2/I', -1) self._dbusservice.add_path('/Ac/ActiveIn/Connected', 1) self._dbusservice.add_path('/Ac/ActiveIn/ActiveInput', 0) self._dbusservice.add_path('/VebusError', 0) self._dbusservice.add_path('/Dc/0/Voltage', -1) self._dbusservice.add_path('/Dc/0/Power', -1) self._dbusservice.add_path('/Dc/0/Current', -1) self._dbusservice.add_path('/Ac/NumberOfPhases', 2) self._dbusservice.add_path('/Alarms/GridLost', 0) # /VebusChargeState <- 1. Bulk # 2. Absorption # 3. Float # 4. Storage # 5. Repeat absorption # 6. Forced absorption # 7. Equalise # 8. Bulk stopped self._dbusservice.add_path('/VebusChargeState', 0) # Some attempts at logging consumption. Float of kwhr since driver start (i think) self._dbusservice.add_path('/Energy/GridToDc', 0) self._dbusservice.add_path('/Energy/GridToAcOut', 0) self._dbusservice.add_path('/Energy/DcToAcOut', 0) self._dbusservice.add_path('/Energy/AcIn1ToInverter', 0) self._dbusservice.add_path('/Energy/AcIn1ToAcOut', 0) self._dbusservice.add_path('/Energy/InverterToAcOut', 0) self._dbusservice.add_path('/Energy/Time', timer()) self._changed = True # create timers (time in msec) gobject.timeout_add(2000, exit_on_error, self._can_bus_txmit_handler) gobject.timeout_add(2000, exit_on_error, self._energy_handler) gobject.timeout_add(20, exit_on_error, self._parse_can_data_handler)
@dbus.service.method(dbus_interface='org.freedesktop.jackvolume') def setPortName(self, p): """sets port (to connect to) name""" global portname dbgPrint("set portname to " + p) portname = p return @dbus.service.method(dbus_interface='org.freedesktop.jackvolume') def getPortName(self): """gets port (to connect to) name""" dbgPrint("portname is " + portname) return portname @dbus.service.method(dbus_interface='org.freedesktop.jackvolume') def Quit(self): """removes this object from the DBUS connection and exits""" global kill kill = 1 self.remove_from_connection() Gtk.main_quit() if client != '': client.deactivate() client.close() return DBusGMainLoop(set_as_default=True) myservice = jvDbusService() Gtk.main()
# ============================================================================= # zeroconf # ============================================================================= _ZC_TYPE = "_remuco._tcp" if linux: import dbus from dbus.mainloop.glib import DBusGMainLoop from dbus.exceptions import DBusException import gobject dbus.set_default_main_loop(DBusGMainLoop()) # Avahi DBus constants (defined here to prevent python-avahi dependency) _DBA_NAME = "org.freedesktop.Avahi" _DBA_INTERFACE_SERVER = _DBA_NAME + ".Server" _DBA_PATH_SERVER = "/" _DBA_INTERFACE_ENTRY_GROUP = _DBA_NAME + ".EntryGroup" _zc_group = None def zc_publish(player, port): """Publish a service for the given player at the given port.""" zc_unpublish() log.debug("publishing zeroconf service")