#!/usr/bin/env python2 """ Connects to Wicd over Dbus to discover connection status. Returns exit codes - 0 for connected 1 for connecting 2 for disconnected """ import dbus bus = dbus.SystemBus() daemon = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon'), 'org.wicd.daemon') info = daemon.GetConnectionStatus() if not (len(info) > 1 and len(info[1]) and info[1][0]): exit(2) # Disconnected if info[1][0] in ('wired', 'wireless'): exit(1) # Connecting exit(0) # Connected
# corrects encoding for the python version used def fix_string(string): if sys.version_info.major == 3: return string else: return string.encode('utf-8') # Output-Format output = fix_string(u'{artist}: {song}') # Read metadata and print lable for polybar bus = dbus.SessionBus() spotify_bus = bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2') spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties') # All data metadata = spotify_properties.Get('org.mpris.MediaPlayer2.Player', 'Metadata') # Artist artist = fix_string( metadata['xesam:artist'][0]) if metadata['xesam:artist'] else '' # Song song = fix_string(metadata['xesam:title']) if metadata['xesam:title'] else '' if not artist and not song: print('') else: print(output.format(artist=artist, song=song))
def __init__(self): self._fts = BUS.get_object('org.gnome.zeitgeist.Engine', '/org/gnome/zeitgeist/index/activity') self.fts = dbus.Interface(self._fts, 'org.gnome.zeitgeist.Index')
def get_gatt_characteristic_interface(): """Return the DBus Interface for a Bluez GATT Characteristic.""" return dbus.Interface( dbus.SystemBus().get_object(constants.BLUEZ_SERVICE_NAME, '/org/bluez/hci0'), constants.GATT_CHRC_IFACE)
def get_advert_manager_interface(): """Return the DBus Interface for a Bluez GATT LE Advertising Manager.""" return dbus.Interface( dbus.SystemBus().get_object(constants.BLUEZ_SERVICE_NAME, '/org/bluez/hci0'), constants.LE_ADVERTISING_MANAGER_IFACE)
return pincode def create_device_reply(device): mainloop.quit() def create_device_error(error): print "PIN Failed" exit(-1) if __name__ == '__main__': dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.bluez.Manager") adapter = dbus.Interface( bus.get_object("org.bluez", manager.DefaultAdapter()), "org.bluez.Adapter") try: device = adapter.FindDevice(sys.argv[1]) adapter.RemoveDevice(device) except: pass path = "/test/agent" agent = Agent(bus, path) mainloop = gobject.MainLoop() if len(sys.argv) > 2:
def get_gatt_manager_interface(): """Return the DBus Interface for a Bluez GATT Manager.""" return dbus.Interface( dbus.SystemBus().get_object(constants.BLUEZ_SERVICE_NAME, '/org/bluez/hci0'), constants.GATT_MANAGER_IFACE)
def dbus_get_device_prop_interface(self, name): proxy = self.bus.get_object(name, "/org/mpris/MediaPlayer2") device_prop = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") return device_prop
def receivedMessage(account, sender, message, conversation, flags): print conversation,", ", sender, "said:", message # Import libraries import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() # Add receivedMessage signal handler bus.add_signal_receiver(receivedMessage, dbus_interface="im.pidgin.purple.PurpleInterface", signal_name="ReceivedImMsg") # set purple object obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") # Printing XMPP accounts for acc in purple.PurpleAccountsGetAllActive(): if purple.PurpleAccountGetProtocolId(acc) == "prpl-jabber": print purple.PurpleAccountGetUsername(acc) # Get account to work with #account_name = raw_input("Choose the account you wish to use today: ") account_name = "[email protected]/" account = purple.PurpleAccountsFind(account_name, "prpl-jabber") # Create new chat with user's defined name #conv_name = raw_input("Choose your buddy name: ") conv_name = "mkorostel" conv = purple.PurpleConversationNew(1, account, conv_name + "@qip.ru")
def __init__(self): # Connect to the bus self.bus = dbus.SessionBus() self.controller = self.bus.get_object(service_name, "/org/jackaudio/Controller") self.iface = dbus.Interface(self.controller, controller_interface_name)
def get_introspect(self): i = dbus.Interface(self.dbus_object, 'org.freedesktop.DBus.Introspectable') return DbusIntrospection.introspect(i.Introspect())
def _station(self): if self._station_if is None: self._station_if = dbus.Interface( self._bus.get_object(IWD_SERVICE, self.device_path), IWD_STATION_INTERFACE) return self._station_if
def open_freebsd(self): import dbus # There should be some way to access the -v arg... verbose = False # this gives us access to the S/N, etc. of the reader that the scanner has found # and the match routines for some of that data, like s/n, vendor ID, etc. d=self.detected_device if not d.serial: raise DeviceError("Device has no S/N. Can't continue") return False vols=[] bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object('org.freedesktop.Hal', '/org/freedesktop/Hal/Manager'), 'org.freedesktop.Hal.Manager') paths = manager.FindDeviceStringMatch('usb.serial',d.serial) for path in paths: objif = dbus.Interface(bus.get_object('org.freedesktop.Hal', path), 'org.freedesktop.Hal.Device') # Extra paranoia... try: if d.idVendor == objif.GetProperty('usb.vendor_id') and \ d.idProduct == objif.GetProperty('usb.product_id') and \ d.manufacturer == objif.GetProperty('usb.vendor') and \ d.product == objif.GetProperty('usb.product') and \ d.serial == objif.GetProperty('usb.serial'): midpath = manager.FindDeviceStringMatch('info.parent', path) dpaths = manager.FindDeviceStringMatch( 'storage.originating_device', path) + manager.FindDeviceStringMatch('storage.originating_device', midpath[0]) for dpath in dpaths: # devif = dbus.Interface(bus.get_object('org.freedesktop.Hal', dpath), 'org.freedesktop.Hal.Device') try: vpaths = manager.FindDeviceStringMatch('block.storage_device', dpath) for vpath in vpaths: try: vdevif = dbus.Interface(bus.get_object('org.freedesktop.Hal', vpath), 'org.freedesktop.Hal.Device') if not vdevif.GetProperty('block.is_volume'): continue if vdevif.GetProperty('volume.fsusage') != 'filesystem': continue volif = dbus.Interface(bus.get_object('org.freedesktop.Hal', vpath), 'org.freedesktop.Hal.Device.Volume') pdevif = dbus.Interface(bus.get_object('org.freedesktop.Hal', vdevif.GetProperty('info.parent')), 'org.freedesktop.Hal.Device') vol = {'node': pdevif.GetProperty('block.device'), 'dev': vdevif, 'vol': volif, 'label': vdevif.GetProperty('volume.label')} vols.append(vol) except dbus.exceptions.DBusException as e: print(e) continue except dbus.exceptions.DBusException as e: print(e) continue except dbus.exceptions.DBusException as e: continue vols.sort(key=lambda x: x['node']) if verbose: print("FBSD: ", vols) mtd=0 for vol in vols: mp = '' if vol['dev'].GetProperty('volume.is_mounted'): mp = vol['dev'].GetProperty('volume.mount_point') else: try: vol['vol'].Mount('Calibre-'+vol['label'], vol['dev'].GetProperty('volume.fstype'), []) loops = 0 while not vol['dev'].GetProperty('volume.is_mounted'): time.sleep(1) loops += 1 if loops > 100: print("ERROR: Timeout waiting for mount to complete") continue mp = vol['dev'].GetProperty('volume.mount_point') except dbus.exceptions.DBusException as e: print("Failed to mount ", e) continue # Mount Point becomes Mount Path mp += '/' if verbose: print("FBSD: mounted", vol['label'], "on", mp) if mtd == 0: self._main_prefix = mp self._main_vol = vol['vol'] if verbose: print("FBSD: main = ", self._main_prefix) if mtd == 1: self._card_a_prefix = mp self._card_a_vol = vol['vol'] if verbose: print("FBSD: card a = ", self._card_a_prefix) if mtd == 2: self._card_b_prefix = mp self._card_b_vol = vol['vol'] if verbose: print("FBSD: card b = ", self._card_b_prefix) # Note that mtd is used as a bool... not incrementing is fine. break mtd += 1 if mtd > 0: return True raise DeviceError(_('Unable to mount the device'))
def test(q, bus, mc): params = dbus.Dictionary( { "account": "*****@*****.**", "password": "******" }, signature='sv') (simulated_cm, account) = create_fakecm_account(q, bus, mc, params) srv_name = 'fu-bar-42' account_iface = dbus.Interface(account, cs.ACCOUNT) account_props = dbus.Interface(account, cs.PROPERTIES_IFACE) # defaults to the empty string assertEquals(account_props.Get(cs.ACCOUNT, 'Service'), '') # set to a new value after creation call_async(q, account_props, 'Set', cs.ACCOUNT, 'Service', srv_name) q.expect_many( EventPattern('dbus-signal', path=account.object_path, signal='AccountPropertyChanged', interface=cs.ACCOUNT, args=[{ 'Service': srv_name }]), EventPattern('dbus-return', method='Set'), ) assertEquals(account_props.Get(cs.ACCOUNT, 'Service'), srv_name) # set to an invalid value (no actual change should occur) # leading non-alphabetic (make sure _ isn't considered alphabetic) call_async(q, account_props, 'Set', cs.ACCOUNT, 'Service', '_fu-bar') q.expect_many(EventPattern('dbus-error', method='Set')) assertEquals(account_props.Get(cs.ACCOUNT, 'Service'), srv_name) # leading non-alphabetic call_async(q, account_props, 'Set', cs.ACCOUNT, 'Service', '.moose') q.expect_many(EventPattern('dbus-error', method='Set')) assertEquals(account_props.Get(cs.ACCOUNT, 'Service'), srv_name) # gregexes have an option to be lenient about trailing newlines: # this makes sure we haven't made that mistake call_async(q, account_props, 'Set', cs.ACCOUNT, 'Service', srv_name + '\n') q.expect_many(EventPattern('dbus-error', method='Set')) assertEquals(account_props.Get(cs.ACCOUNT, 'Service'), srv_name) # set to an empty string call_async(q, account_props, 'Set', cs.ACCOUNT, 'Service', '') q.expect_many(EventPattern('dbus-return', method='Set')) assertEquals(account_props.Get(cs.ACCOUNT, 'Service'), '') # test creation with a service account_manager = bus.get_object(cs.AM, cs.AM_PATH) am_iface = dbus.Interface(account_manager, cs.AM) service_prop = dbus.Dictionary({ cs.ACCOUNT + '.Service': "moomin-troll", }, signature='sv') call_async( q, am_iface, 'CreateAccount', 'fakecm', # Connection_Manager 'fakeprotocol', # Protocol 'fakeaccount', # Display_Name params, # Parameters service_prop, # Properties ) ret = q.expect('dbus-return', method='CreateAccount') path = ret.value[0] account = bus.get_object(cs.tp_name_prefix + '.AccountManager', path) if_props = dbus.Interface(account, cs.PROPERTIES_IFACE) props = if_props.GetAll(cs.ACCOUNT) assertEquals(props.get('Service'), 'moomin-troll') # attempt creation with a bogus service service_prop = dbus.Dictionary({cs.ACCOUNT + '.Service': "1337"}, signature='sv') call_async( q, am_iface, 'CreateAccount', 'fakecm', # Connection_Manager 'fakeprotocol', # Protocol 'fakeaccount', # Display_Name params, # Parameters service_prop, # Properties ) ret = q.expect('dbus-error', method='CreateAccount')
def set_trusted(path): props = dbus.Interface(bus.get_object("org.bluez", path), "org.freedesktop.DBus.Properties") props.Set("org.bluez.Device1", "Trusted", True)
#!/usr/bin/env python3 import dbus import argparse jscript = """ var allDesktops = desktops(); print (allDesktops); for (i=0;i<allDesktops.length;i++) { d = allDesktops[i]; d.wallpaperPlugin = "org.kde.image"; d.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General"); d.writeConfig("Image", "file://%s") } """ parser = argparse.ArgumentParser(description='KDE Wallpaper setter') parser.add_argument('file', help='Wallpaper file name') args = parser.parse_args() bus = dbus.SessionBus() plasma = dbus.Interface(bus.get_object('org.kde.plasmashell', '/PlasmaShell'), dbus_interface='org.kde.PlasmaShell') plasma.evaluateScript(jscript % args.file)
def dev_connect(path): dev = dbus.Interface(bus.get_object("org.bluez", path), "org.bluez.Device1") dev.Connect()
def connect(self, screenlet_settings): proxy_obj = self.session_bus.get_object(self.this_mpris_ns, self.this_mpris_iroot) self.playerAPI = dbus.Interface(proxy_obj, self.this_mpris_iface) proxy_obj2 = self.session_bus.get_object(self.ns2, self.iroot2) self.playerAPI2 = dbus.Interface(proxy_obj, self.iface2)
def assertNoURI(ft_channel): ft_props = dbus.Interface(ft_channel, cs.PROPERTIES_IFACE) uri = ft_props.Get(cs.CHANNEL_TYPE_FILE_TRANSFER, 'URI') assertEquals('', uri)
def __init__(self, server, **kwargs): if server.coherence.config.get('use_dbus', 'no') != 'yes': raise Exception, 'this backend needs use_dbus enabled in the configuration' BackendStore.__init__(self, server, **kwargs) self.config = kwargs self.name = kwargs.get('name', 'Tracker') self.update_id = 0 self.token = None self.songs = 0 self.albums = 0 self.artists = 0 self.playlists = 0 self.genres = 0 self.videos = 0 self.images = 0 self.bus = dbus.SessionBus() tracker_object = self.bus.get_object(BUS_NAME, OBJECT_PATH) self.tracker_interface = dbus.Interface(tracker_object, 'org.freedesktop.Tracker') self.search_interface = dbus.Interface( tracker_object, 'org.freedesktop.Tracker.Search') self.keywords_interface = dbus.Interface( tracker_object, 'org.freedesktop.Tracker.Keywords') self.metadata_interface = dbus.Interface( tracker_object, 'org.freedesktop.Tracker.Metadata') self.query_id = -1 self.containers = {} self.tracks = {} self.containers[ROOT_CONTAINER_ID] = \ Container(ROOT_CONTAINER_ID,-1,self.name,store=self) def queries_finished(r): louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self) def queries_failed(r): error = '' louie.send('Coherence.UPnP.Backend.init_failed', None, backend=self, msg=error) services = kwargs.get('service', 'Music,Videos,Images') services = map(lambda x: x.strip().lower(), services.split(',')) l = [] mapping = { 'music': self.get_tracks, 'videos': self.get_videos, 'images': self.get_images } for service in services: try: l.append(mapping[service]()) except KeyError: self.warning('Wrong Tracker service definition - %r' % service) if len(l) > 0: dl = defer.DeferredList(l) dl.addCallback(queries_finished) dl.addErrback(lambda x: louie.send( 'Coherence.UPnP.Backend.init_failed', None, backend=self, msg='Connection to Tracker service(s) failed!')) else: louie.send('Coherence.UPnP.Backend.init_failed', None, backend=self, msg='No Tracker service defined!')
def get_gatt_service_interface(): """Return the DBus Interface for a Bluez GATT Service.""" return dbus.Interface( dbus.SystemBus().get_object(constants.BLUEZ_SERVICE_NAME, '/org/bluez/hci0'), constants.GATT_SERVICE_IFACE)
def go(): ## I think we need an object here which will poll until told to stop. ## Register some callbacks to spit out servers print "Here" import sys import time import dbus, gobject, avahi from dbus.mainloop.glib import DBusGMainLoop import string serviceType = "_wfut._tcp" servicePort = 0; serviceTXT = "" domain = "" host = "" ## Map of discovered servers servers = {} def service_add(interface, protocol, name, type, domain, flags): print "found server" ## Find out more info obj_path = server.ServiceResolverNew(interface, protocol, name, type, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0)) resolver = dbus.Interface(bus.get_object(avahi.DBUS_NAME, obj_path), avahi.DBUS_INTERFACE_SERVICE_RESOLVER) ## Hook up callbacks to 'Found' resolver.connect_to_signal('Found', found) def found(interface, protcol, name, type, domain, host, aprotocol, address, port, txt, flags): ## Construct a server url from address and port number. ## Uses '[' ']' incase of IPv6 addresses. servers[name] = "".join([ "http://", "[" , address, "]", ":", str(port)]) ## Look for a "url" txt field to override the one constructed above. txt_arr = avahi.txt_array_to_string_array(txt) for rec in txt_arr: (key, value) = rec.split("=") if key == "url": servers[name] = value print "Found server: " + servers[name] if True: print "Here" DBusGMainLoop( set_as_default=True ) main_loop = gobject.MainLoop() bus = dbus.SystemBus() ## TODO: Hook up service added / removed global server server = dbus.Interface( bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ), avahi.DBUS_INTERFACE_SERVER ) ## Find services from any interface and protocol interface = avahi.IF_UNSPEC protocol = avahi.PROTO_UNSPEC ## Use local domain. domain = "local" ## Call method to create new browser, and get back an object ## path for it. obj_path = server.ServiceBrowserNew(interface, protocol, serviceType, domain, dbus.UInt32(0)) ## Create browser interface for the new object browser = dbus.Interface(bus.get_object(avahi.DBUS_NAME, obj_path), avahi.DBUS_INTERFACE_SERVICE_BROWSER) ## Hook up signal for new found services browser.connect_to_signal('ItemNew', service_add) try: context = main_loop.get_context() ## TODO: loop for short time period while (context.pending()): print "tick" time.sleep(0.5) # Handle commands here context.iteration(True) ## TODO: Turn off avahi ## Offer choices to user index = 0; options = []; for (key, value) in servers.iteritems(): index = index + 1; print(string.join(["Found (", str(index), ") ", key, " -> ", value])) options.append(key) while True: try: print "Pick Server: ", opt = sys.stdin.readline(); opt = int(opt) - 1; break; except Exception as e: print e ## get selected server option choice = options[opt] server = servers[choice]; return server ## Fall back to original code with new server choice except KeyboardInterrupt: pass
def get_gatt_descriptor_interface(): """Return the DBus Interface for a Bluez GATT Descriptor.""" return dbus.Interface( dbus.SystemBus().get_object(constants.BLUEZ_SERVICE_NAME, '/org/bluez/hci0'), constants.GATT_DESC_IFACE)
def kill_daemon(*args): bus = dbus.SystemBus() remote_object = bus.get_object("edu.duke.linux.yum", "/Updatesd") iface = dbus.Interface(remote_object, "edu.duke.linux.yum") remote_object.ShutDown(dbus_interface="edu.duke.linux.yum")
def get_managed_objects(): """Return the objects currently managed by the DBus Object Manager.""" bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object(constants.BLUEZ_SERVICE_NAME, '/'), constants.DBUS_OM_IFACE) return manager.GetManagedObjects()
def check_updates(*args): bus = dbus.SystemBus() remote_object = bus.get_object("edu.duke.linux.yum", "/Updatesd") iface = dbus.Interface(remote_object, "edu.duke.linux.yum") remote_object.CheckNow(dbus_interface="edu.duke.linux.yum")
def __init__(self): self.hamster = BUS.get_object(HAMSTER_URI, HAMSTER_PATH) self.iface = dbus.Interface(self.hamster, dbus_interface=HAMSTER_URI)
"--timeout", action="store", type="int", dest="timeout", default=60000) (options, args) = parser.parse_args() if options.capability: capability = options.capability path = "/test/agent" agent = Agent(bus, path) mainloop = GObject.MainLoop() obj = bus.get_object(BUS_NAME, "/org/bluez") manager = dbus.Interface(obj, "org.bluez.AgentManager1") manager.RegisterAgent(path, capability) print("Agent registered") # Fix-up old style invocation (BlueZ 4) if len(args) > 0 and args[0].startswith("hci"): options.adapter_pattern = args[0] del args[:1] if len(args) > 0: device = bluezutils.find_device(args[0], options.adapter_pattern) dev_path = device.object_path agent.set_exit_on_release(False) device.Pair(reply_handler=pair_reply, error_handler=pair_error,
def GetObjectInterface(self, kind, path): return dbus.Interface( self.bus.get_object(FlimFlam.SHILL_DBUS_INTERFACE, path), FlimFlam.SHILL_DBUS_INTERFACE + "." + kind)
r'spampd.service', r'sshd.service', r'svnserve.service', r'synapse.service', r'system-rsyncd.slice', r'unbound.service', r'uwsgi@.*.service', r'zabbix-agent.service', r'zabbix-server-pgsql.service', r'fail2ban.service', ] bus = dbus.SystemBus() systemd1 = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1') systemd1_manager = dbus.Interface( systemd1, dbus_interface='org.freedesktop.systemd1.Manager') units = systemd1_manager.ListUnits() discovered = [] def get_unit_prop_interface(obj, interface, propname): try: return obj.Get(interface, propname) except dbus.exceptions.DBusException as err: if err.get_dbus_name() == 'org.freedesktop.DBus.Error.UnknownProperty': return None else: raise