def main(): """ The script's main function. """ # Sets up exception hook sys.excepthook = fail # Gets script arguments args = get_args() # If the "version" argument is present, prints version and exit if (args.version): version() # Attempts to connect to the bus specified via command line arguments if (args.system): bus = pydbus.SystemBus() elif (args.session): bus = pydbus.SessionBus() else: bus = pydbus.connect(args.bus) # Request bus name, register object and run loop loop = GObject.MainLoop() bus.request_name(args.name) bus.register_object('/org/mpris/MediaPlayer2', MediaPlayer2(args.identity), MediaPlayer2.__doc__) vprint('Registered object to the message bus.') loop.run()
def main(argv): # connect to session DBus bus = pydbus.SessionBus() # This is very ugly, but the only way (I know) to expose the iBuddy to the # method processing the message from Pidgin global ibuddy # register a callback for messages that are received try: ibuddy = bus.get("nl.tjaldur.IBuddy", "/nl/tjaldur/IBuddy") except: ibuddy = None if ibuddy is None: print("iBuddy not found, exiting", file=sys.stderr) sys.exit(1) # register a callback for messages that are received purple = bus.get("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") purple.ReceivedImMsg.connect(processmsg) gi.repository.GObject.MainLoop().run() # finally reset the i-buddy again ibuddy.ExecuteBuddyCommand("RESET")
def get_dbus(dbus=[None], gshell=[None], gext=[None]): import pydbus if not dbus[0]: dbus[0] = pydbus.SessionBus() gshell[0] = dbus[0].get('org.gnome.Shell', '/org/gnome/Shell') gext[0] = gshell[0]['org.gnome.Shell.Extensions'] return (gshell[0], gext[0])
def connect(self) -> None: """ Connects to the DBus session. Tries to access the proxy object and configures the call on property changes. A `ConnectionNotReady` exception is thrown if no Spotify bus exists or if no song is playing. """ self._logger.info("Connecting") self._bus = pydbus.SessionBus() try: self._obj = self._bus.get('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2') except GLib.Error: raise ConnectionNotReady("No Spotify session currently running") self._loop = GLib.MainLoop() self._disconnect_obj = self._obj.PropertiesChanged.connect( self._on_properties_changed) try: self._refresh_metadata() except IndexError: raise ConnectionNotReady("No song is currently playing")
def run(self): log('daemon thread') state = self.app.state if self.app.state.bus == 'system': self.bus = pydbus.SystemBus() else: self.bus = pydbus.SessionBus() log('daemon waiting for ({}) dbus...'.format(self.app.state.bus)) self.signal = exception_waitloop(self.get_message_bus, GLib.Error, 60) if not self.signal: log('dbus err') npyscreen.notify_wait( 'Unable to get signal {} bus. Messaging functionality will not function.' .format(self.app.state.bus), title='Error in SignalDaemonThread') exit(1) log('got daemon dbus') msgRcv = lambda timestamp, source, groupID, message, attachments: self.msgRcv( timestamp, source, groupID, message, attachments) loop = GLib.MainLoop() self.signal.onMessageReceived = msgRcv log('daemon starting loop') loop.run()
def run(self): log('message thread') if self.app.state.bus == 'system': self.bus = pydbus.SystemBus() else: self.bus = pydbus.SessionBus() log('waiting for ({}) dbus...'.format(self.app.state.bus)) self.signal = exception_waitloop(self.get_message_bus, GLib.Error, 60) if not self.signal: log('dbus err') npyscreen.notify_wait( 'Unable to get signal {} bus. Messaging functionality will not function.' .format(self.app.state.bus), title='Error in SignalDaemonThread') exit(1) log('got dbus') # self.signal.onMessageReceived while True: item = self.queue.get() log('queue item', item) if 'exit' in item: break self.do_action(**item) self.queue.task_done() log('message thread exit')
def send_notification(device_type : str, status : BatteryState, percentage : int, battery_level : BatteryLevel, time_to_full : int, time_to_empty : int, icon : str) -> None: """ Sends a desktop notification based on the given information """ if battery_level == BatteryLevel.NONE: level_string = "" else: level_string = f" {str(battery_level)}" summary = f"{str(device_type)}{level_string}" body = f"{str(device_type)}{level_string}: {percentage}%\n{str(status)}" if time_to_full: body += f", full in {str(datetime.timedelta(seconds=time_to_full))}" if device.TimeToEmpty: body += f", empty in {str(datetime.timedelta(seconds=time_to_empty))}" pydbus.SessionBus().get(".Notifications").Notify( "Battery Alert", 0, icon, summary, body, [], {}, -1 )
def pydbus_server(): loop = MainLoop() bus = pydbus.SessionBus() try: bus.get('pydbus.unittest',timeout=1) except: with bus.publish("pydbus.unittest", PyDbusUnitTestService(loop)): loop.run()
def list_inhibitors(): bus = pydbus.SessionBus() sm = bus.get(bus_name='org.gnome.SessionManager') xs = sm.GetInhibitors() for x in xs: p = bus.get(bus_name='org.gnome.SessionManager', object_path=x) print( f'{p.GetAppId()} {p.GetReason()} flags={"|".join(reasons(p.GetFlags()))}' )
def __init__(self, bluetooth, hfp): self.bus = pydbus.SessionBus() self.obex = self.bus.get('org.bluez.obex', '/org/bluez/obex') self.bluetooth = bluetooth self.transfer = None self.phonebook = [] self.callhistory = [] hfp.bind(connected=self.on_connected_change) self.on_connected_change(self, hfp.connected)
def set_wallpaper(self, path): final_path = f'/tmp/wallify_{self.tick}.png' bus = pydbus.SessionBus() bus.autoclose = True plasma = bus.get('org.kde.plasmashell', '/PlasmaShell') shutil.copyfile(path, final_path) plasma.evaluateScript(KDE_SCRIPT.replace('IMAGE_PATH', final_path)) self.tick += 1 self.tick %= 2
def __init__(self, logger, enable_audio=False, enable_mouse=False): super(Recorder, self).__init__() self.logger = logger self.enable_audio = enable_audio self.enable_mouse = enable_mouse self.dbus = pydbus.SessionBus() self.shell_screencast = self.dbus.get("org.gnome.Shell.Screencast", "/org/gnome/Shell/Screencast") self.processes = list() self.filename = None
def __init__(self): try: bus = pydbus.SystemBus() self._obj = bus.get(DBUS_SERVICE) except gi.repository.GLib.Error: logging.warning( "Failed to retrieve D-BUS service from system bus; falling back to session bus" ) bus = pydbus.SessionBus() self._obj = bus.get(DBUS_SERVICE)
def __init__(self, on_active_changed: callable): session_bus = pydbus.SessionBus() screensaver_list = [ "org.gnome.ScreenSaver", "org.cinnamon.ScreenSaver", "org.kde.screensaver", "org.freedesktop.ScreenSaver" ] for s in screensaver_list: try: proxy = session_bus.get(s) proxy.ActiveChanged.connect(on_active_changed) except GLib.Error: pass
def setup(self): self.bus = pydbus.SessionBus() self.bus.get('org.freedesktop.DBus') match_rules = [ "interface='org.freedesktop.Notifications', member='Notify'", "interface='org.freedesktop.Notifications', member='NotificationClosed'", "interface='org.gtk.Notifications', member='AddNotification'", "interface='org.gtk.Notifications', member='RemoveNotification'" ] self.bus.get('org.freedesktop.DBus').BecomeMonitor(match_rules, 0) self.bus.con.add_filter(self.handle_notification) return True
def setup(): global HOME, db_conn, browser_bus HOME = getenv('HOME', '/home/pi') signal(SIGUSR1, sigusr1) signal(SIGALRM, sigalrm) load_settings() db_conn = db.conn(settings['database']) load_browser() bus = pydbus.SessionBus() browser_bus = bus.get('screenly.webview', '/Screenly')
def __init__(self, state_port): self.state_port = state_port loop = gi.repository.GLib.MainLoop() try: bus = pydbus.SystemBus() bus.publish(DBUS_SERVICE, self) except gi.repository.GLib.Error: logging.warning( "Failed to publish D-BUS service on system bus; falling back to session bus" ) bus = pydbus.SessionBus() bus.publish(DBUS_SERVICE, self) loop.run()
def inhibit(secs): bus = pydbus.SessionBus() # we could leave out object_path because it defaults to bus_name # with . replaced by / ... sm = bus.get(bus_name='org.gnome.SessionManager', object_path='/org/gnome/SessionManager') # 'org.gnome.SesssionManager' is also the interface name ... xid = 0 # again, we could leave out interface name, as it defaults to that sm['org.gnome.SessionManager'].Inhibit( 'inhibit.py', xid, 'user requested idle-off from terminal', INHIBIT_IDLE) time.sleep(secs)
def __init__(self, address, strips, bus_type="system", socket=None): super(DBusServer, self).__init__() self.strips = [] if (hasattr(strips, "__iter__")): self.strips = strips else: self.strips.append(strips) if (bus_type == "System"): self.bus = pydbus.SystemBus() elif (bus_type == "Session"): self.bus = pydbus.SessionBus() else: raise AttributeError("The bus type is not valid") self.address = address
def launch_dbus_filebrowser(uri): import pydbus import socket uid = "{}{}_TIME{}".format(socket.gethostname(), os.getpid(), int(time.time())) bus = pydbus.SessionBus() proxy = bus.get("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1") iface = proxy['org.freedesktop.FileManager1'] logger.info( "Dbus: calling org.freedesktop.FileManager1.ShowFolders" "(%s, %s)", str([uri]), str(uid)) iface.ShowFolders([uri], uid)
def __init__(self, **config): base._Widget.__init__(self, bar.CALCULATED, **config) self.add_defaults(UnitStatus.defaults) self.add_defaults(base.PaddingMixin.defaults) self.add_defaults(base.MarginMixin.defaults) if self.indicator_size is not None: self.indicator_size = max(self.indicator_size, 1) self.colours = {} for state, cols in self.state_map.items(): self.colours[state] = tuple(getattr(self, col) for col in cols) if self.bus_name == "session": self.bus = pydbus.SessionBus() else: self.bus = pydbus.SystemBus() self.systemd = self.bus.get(".systemd1")
def __init__(self): try: import pydbus self.bus = pydbus.SessionBus() except ModuleNotFoundError: logger.info( "pydbus not installed, GNOME-Shell Wayland support disabled") self.bus = False self.gnome_shell = None if self.bus: import gi.repository.GLib try: self.gnome_shell = self.bus.get("org.gnome.Shell") self._setup_gnome() except gi.repository.GLib.Error: self.gnome_shell = None
def connect_api(self) -> None: """ Connects to the DBus session. Tries to access the proxy object and configures the call on property changes. """ self._bus = pydbus.SessionBus() self._bus_name, self._obj = self._get_player() self.player_name = self._obj['org.mpris.MediaPlayer2'].Identity self._player_interface = self._obj['org.mpris.MediaPlayer2.Player'] try: self._refresh_metadata() except IndexError: raise ConnectionNotReady("Metadata unavailable") self._start_event_loop()
def publish(self): bus_type = BUS_TYPE logger.debug(f"Connecting to D-Bus {bus_type} bus...") if bus_type == "system": bus = pydbus.SystemBus() else: bus = pydbus.SessionBus() logger.info(f"MPRIS server connected to D-Bus {bus_type} bus") self._publication_token = bus.publish( f"org.mpris.MediaPlayer2.{self.dbus_name}", ("/org/mpris/MediaPlayer2", self.root), ("/org/mpris/MediaPlayer2", self.player), ("/org/mpris/MediaPlayer2", self.playlists), ("/org/mpris/MediaPlayer2", self.tracklist) )
def setup_hotspot(): bus = pydbus.SessionBus() pattern_include = re.compile("wlan*") pattern_exclude = re.compile("ScreenlyOSE-*") wireless_connections = get_active_connections(bus) if wireless_connections is None: return wireless_connections = filter( lambda c: not pattern_exclude.search(str(c['Id'])), filter( lambda c: pattern_include.search(str(c['Devices'])), wireless_connections ) ) # Displays the hotspot page if not path.isfile(HOME + INITIALIZED_FILE) and not gateways().get('default'): if len(wireless_connections) == 0: url = 'http://{0}/hotspot'.format(LISTEN) view_webpage(url) # Wait until the network is configured while not path.isfile(HOME + INITIALIZED_FILE) and not gateways().get('default'): if len(wireless_connections) == 0: sleep(1) wireless_connections = filter( lambda c: not pattern_exclude.search(str(c['Id'])), filter( lambda c: pattern_include.search(str(c['Devices'])), get_active_connections(bus) ) ) continue if wireless_connections is None: sleep(1) continue break wait_for_node_ip(5)
def get_spotify_track(): session_bus = pydbus.SessionBus() try: spotify_base = "/org/mpris/MediaPlayer2" spotify = session_bus.get("org.mpris.MediaPlayer2.spotify", spotify_base) return spotify["org.mpris.MediaPlayer2.Player"].Metadata["mpris:trackid"] except gi.repository.GLib.Error as err: spotify_not_running = ( "g-dbus-error-quark: " "GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: " "The name org.mpris.MediaPlayer2.spotify " "was not provided by any .service files (2)") spotify_has_quit = ( "g-dbus-error-quark: " "GDBus.Error:org.freedesktop.DBus.Error.NoReply: " "Message recipient disconnected from message bus without replying (4)" ) if str(err) == spotify_not_running: return "" if str(err) == spotify_has_quit: return "" raise
def connect_api(self) -> None: """ Connects to the DBus session. Tries to access the proxy object and configures the call on property changes. """ self._bus = pydbus.SessionBus() self._bus_name, self._obj = self._get_player() # Some MPRIS players don't support the position feature, so this # checks if it's in the blacklist to act accordingly when the # position is requested. position_blacklist = ('org.mpris.MediaPlayer2.spotify', ) self._no_position = self._bus_name in position_blacklist self._player_interface = self._obj['org.mpris.MediaPlayer2.Player'] try: self._refresh_metadata() except IndexError: raise ConnectionNotReady("No song is currently playing") self._start_event_loop()
def main(): """ The script's main function. """ # Sets up exception hook sys.excepthook = fail # Gets script arguments args = get_args() # If the "version" argument is present, prints version and exit if (args.version): version() # Creates a list for storing data on found players player_list = list() # Attempts to connect to the bus specified via command line arguments if (args.system): bus = pydbus.SystemBus() elif (args.session): bus = pydbus.SessionBus() else: bus = pydbus.connect(args.bus) # Gets names and proxy objects, and appends them to the list of found # players names = get_mpris_names(bus) for name in names: proxy = get_proxy_object(bus, name) player_list.append({'name': name, 'proxy': proxy}) # Prints information about each player found for player in player_list: print_player_info(player, args.color)
def main(argv): parser = argparse.ArgumentParser() # options for the commandline parser.add_argument("-c", "--config", action="store", dest="cfg", help="path to configuration file", metavar="FILE") parser.add_argument("-k", "--key", action="store", dest="key", help="consumer key", metavar="KEY") parser.add_argument("-s", "--secret", action="store", dest="secret", help="consumer secret", metavar="SECRET") parser.add_argument("-t", "--token", action="store", dest="token", help="access token", metavar="KEY") parser.add_argument("-a", "--accesssecret", action="store", dest="accesssecret", help="access secret", metavar="SECRET") args = parser.parse_args() # first some sanity checks for the configuration file if args.cfg is None: parser.error("Configuration file missing") if not os.path.exists(args.cfg): parser.error("Configuration file does not exist") if args.key is None: parser.error("Consumer key missing") if args.secret is None: parser.error("Consumer secret missing") if args.token is None: parser.error("Access token missing") if args.accesssecret is None: parser.error("Access secret missing") # then parse the configuration file config = configparser.ConfigParser() configfile = open(args.cfg, 'r') try: config.readfp(configfile) except Exception: print("Cannot read configuration file", file=sys.stderr) sys.exit(1) buddy_config = {} for section in config.sections(): if section == 'ibuddy': try: productid = int(config.get(section, 'productid')) buddy_config['productid'] = productid except: pass buddy_config['reset_position'] = False try: reset_position_val = config.get(section, 'reset_position') if reset_position_val == 'yes': buddy_config['reset_position'] = True except: pass if section == 'twitter': pass # get a reference to DBus bus = pydbus.SessionBus() # register a callback for messages that are received try: ibuddy = bus.get("nl.tjaldur.IBuddy", "/nl/tjaldur/IBuddy") except: ibuddy = None # get notifications notifications = bus.get('.Notifications') # create a twitter api endpoint api = twitter.Api(consumer_key=args.key, consumer_secret=args.secret, access_token_key=args.token, access_token_secret=args.accesssecret, sleep_on_rate_limit=True) # set of timestamps to ignore ignorelist = set() verbose = True magnitudemin = 1.5 # loop magnitudere = re.compile('(\d\.\d) magnitude #earthquake') while (True): curtime = calendar.timegm(time.gmtime()) if verbose: print("Current time:", time.asctime(time.localtime(curtime))) sys.stdout.flush() # get earthquake data from a Twitter account try: quakes = api.GetUserTimeline(screen_name='quakestoday') except: if verbose: print("Some error occured, sleeping for 60 seconds", file=sys.stderr) sys.stderr.flush() time.sleep(60) continue for q in quakes: # only process the most recent ones that # happened in the last 15 minutes = 900 seconds if curtime - q.created_at_in_seconds > 900: continue quakedata = q.AsDict() if quakedata['id'] in ignorelist: continue magnituderes = magnitudere.match(quakedata['text']) if magnituderes is None: continue magnitude = float(magnituderes.groups()[0]) if magnitude < magnitudemin: continue shakelength = int(magnitude * 2) if 'place' in quakedata: location = quakedata['place']['country'] else: location = 'unspecified' notifications.Notify( 'test', 0, 'dialog-information', "New quake (%.1f) in %s" % (magnitude, location), "Time: %s, with magnitude %.1f" % (time.asctime( time.localtime(q.created_at_in_seconds)), magnitude), [], {}, 5000) if verbose: print('Time %s, location: %s, magnitude %.1f\n' % (time.asctime(time.localtime( q.created_at_in_seconds)), location, magnitude)) sys.stdout.flush() if ibuddy is not None: try: panic(ibuddy, shakelength) except: pass ignorelist.add(quakedata['id']) time.sleep(0.5) time.sleep(60) # finally reset the i-buddy again ibuddy.ExecuteBuddyCommand("RESET")
def run(self): bus = pydbus.SessionBus() spotify = bus.get('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2') spotify.PropertiesChanged.connect(self.on_track_info) gi.repository.GLib.MainLoop().run()