def _start_uinput_bridge(self):
     """
     Connect to a running uinput bridge. If none is running, we invoke one
     using dbus activation or (if activation is not present) we invoke
     uinputbridge our self.
     """
     dbus_db = dinterface(dbus.SessionBus(), 
                          "org.freedesktop.DBus", 
                          "/", 
                          "org.freedesktop.DBus")
     if not "org.uinputbridge" in dbus_db.ListNames() and \
        not "org.uinputbridge" in dbus_db.ListActivatableNames():
         gobject.spawn_async([self.path.get_binfile("uinputbridge")],
                             flags=gobject.SPAWN_STDOUT_TO_DEV_NULL | 
                                   gobject.SPAWN_STDERR_TO_DEV_NULL )
         count = 0
         while count < 10:
             count += 1
             if "org.uinputbridge" in dbus_db.ListNames():
                 count = 11
             time.sleep(1)
         if count == 10:
             raise UinputServiceStartException()
     self.uinputbridge = dinterface(dbus.SessionBus(), 
                                    "org.uinputbridge", 
                                    "/UInputBridge", 
                                    "org.uinputbridge")
Esempio n. 2
0
 def _lookup_bluetooth_name(bluetooth_address):
     # TODO: Handle no adapters
     # TODO: Handles RequestDefered return type + NotAvailable
     bluez_manager = dinterface(dbus.SystemBus(), 'org.bluez', '/org/bluez', 'org.bluez.Manager')
     try:
         default_adapter = dinterface(dbus.SystemBus(), 'org.bluez', bluez_manager.DefaultAdapter(), 'org.bluez.Adapter')
         return default_adapter.GetRemoteName(bluetooth_address)
     except dbus.exceptions.DBusException:
         return bluetooth_address
 def _start_uinput_bridge(self):
     db = dinterface(dbus.SessionBus(), "org.freedesktop.DBus", "/", "org.freedesktop.DBus")
     if not "org.uinputbridge" in db.ListNames() and \
        not "org.uinputbridge" in db.ListActivatableNames():
         gobject.spawn_async([self.path.get_binfile("uinputbridge")],
                             flags=gobject.SPAWN_STDOUT_TO_DEV_NULL | 
                                   gobject.SPAWN_STDERR_TO_DEV_NULL )
         count = 0
         while count < 10:
             count += 1
             if "org.uinputbridge" in db.ListNames():
                 count = 11
             time.sleep(1)
         if count == 10:
             raise UinputServiceStartException()
     self.uinputbridge = dinterface(dbus.SessionBus(), "org.uinputbridge", "/UInputBridge", "org.uinputbridge")
Esempio n. 4
0
    def __init__(self):
        self.bluez_manager = dinterface(dbus.SystemBus(), "org.bluez", "/org/bluez", "org.bluez.Manager")
        self.bluez_manager.InterfaceVersion()
        self.config = config()
        self.adapter = {}
        self.menu = {}
        self.bluez_manager.connect_to_signal("AdapterAdded", self._bluez_adapter_added)
        self.bluez_manager.connect_to_signal("AdapterRemoved", self._bluez_adapter_removed)
        self.menu["bz_visible"] = {"title": _("Bluetooth visible"), "callback": (self._bluez_switch_visible, 0)}
        self.menu["bz_shorttime"] = {
            "title": _("Bluetooth visible (automatic hiding)"),
            "callback": (self._bluez_switch_visible, 180),
        }
        self.menu["bz_invisible"] = {"title": _("Bluetooth invisible"), "callback": (self._bluez_switch_visible, -1)}

        for menu in self.menu.values():
            menuitem = gtk.CheckMenuItem(menu["title"])
            menuitem.set_draw_as_radio(1)
            menuitem.set_sensitive(0)
            menu["handler"] = menuitem.connect("toggled", *menu["callback"])
            menu["menuitem"] = menuitem

        self.menu_list = [i["menuitem"] for i in self.menu.values()]
        menuitem = gtk.SeparatorMenuItem()
        self.menu_list.append(menuitem)
        self.set_menus_visible(self.config.get_config_item_fb("show-bluetooth", True))
        self._bluez_init_adapter()
Esempio n. 5
0
 def _register_bluez_signals(self):
     """Register the dbus signals from dbus to register the addition and
     removal of bluetooth adapters"""
     if not BTServer.is_bluez_up():
         return
     manager = dinterface(dbus.SystemBus(), 'org.bluez', '/', 'org.bluez.Manager')
     manager.connect_to_signal("AdapterAdded", self.cb_adapter_added)
Esempio n. 6
0
 def call(self):
     if(self.bus):
         self.logger.debug(str((self.bus, self.service, self.object, self.interface)))
         iface = dinterface(self.bus, self.service, self.object, self.interface)
         # This is intendet (black magic, but has to be called this way!): 
         # pylint: disable-msg=W0142
         iface.__getattr__(self.method).__call__(*self.arguments)
Esempio n. 7
0
 def __init__(self, adapter):
     gobject.GObject.__init__(self)
     self.diface = dinterface(dbus.SystemBus(), "org.bluez", adapter, "org.bluez.Adapter")
     self.mode = self.diface.GetMode()
     self.discoverabletimeout = self.diface.GetDiscoverableTimeout()
     # This is a known memory leak:
     self.diface.connect_to_signal("ModeChanged", self._update_adapter_mode)
     self.diface.connect_to_signal("DiscoverableTimeoutChanged", self._update_adapter_timeout)
     # This object won't go out of scope, but we can't disconnect with 0.7 bindings
     # As the above signal is not fired ... we poll every half second
     self.timeout_poll = gobject.timeout_add(500, self._update_timeout)
Esempio n. 8
0
    def _advertise_service(self, state=False):
        """Advertise service via SDP"""
        if not state and self.advertise_id:
            if(type(self.advertise_id) != type({})):
                bluez_db = dinterface(dbus.SystemBus(), 'org.bluez', '/org/bluez', 'org.bluez.Database')
                self.advertise_id = bluez_db.RemoveServiceRecord(self.advertise_id)
            else:
                self.logger.debug("Entered new codepath for new bluez api")
                manager = dinterface( dbus.SystemBus(), 'org.bluez', '/', 'org.bluez.Manager')
                active_connectors = manager.ListAdapters();
                for connector_object in self.advertise_id:
                    if not connector_object in active_connectors:
                        continue
                    connector_interface = dinterface( dbus.SystemBus(), 
                                                      'org.bluez', 
                                                      connector_object,
                                                      'org.bluez.Service')
                    connector_interface.RemoveRecord(self.advertise_id[connector_object]);
            self.advertise_id = None;
        elif state and not self.advertise_id:
            service_record = \
"""
<?xml version="1.0" encoding="UTF-8" ?>
<record>
        <attribute id="0x0001">
             <uuid value="%(serviceid)s" />
        </attribute>
        <attribute id="0x0004">
                <sequence>
                        <sequence>
                                <uuid value="0x0100" />
                        </sequence>
                        <sequence>
                                <uuid value="0x0003" />
                                <uint8 value="%(channel)i" />
                        </sequence>
                </sequence>
        </attribute>
        <attribute id="0x0100">
            <text value="%(name)s" name="name"/>
        </attribute>
</record>
""" % {'serviceid': self.serverid, 
       'name': self.name, 
       'channel': int(self.port) }
            self.logger.debug('Trying to register service: %s' % service_record)
            try:
                bluez_db = dinterface(dbus.SystemBus(), 'org.bluez', '/org/bluez', 'org.bluez.Database')
                self.advertise_id = bluez_db.AddServiceRecordFromXML(service_record)
            except dbus.DBusException:
                self.advertise_id = {};
                self.logger.debug("Entered new codepath for new bluez api")
                manager = dinterface( dbus.SystemBus(), 'org.bluez', '/', 'org.bluez.Manager')
                for connector_object in manager.ListAdapters():
                    connector_interface = dinterface( dbus.SystemBus(), 
                                                      'org.bluez', 
                                                      connector_object,
                                                      'org.bluez.Service')
                    self.advertise_id[connector_object] = connector_interface.AddRecord(service_record);
Esempio n. 9
0
    def __init__(self, bus, interface, service):
        self.lbrc_core = dinterface(bus, service, "/core", interface)
        self.lbrc_profile = dinterface(bus, service, "/profile", interface)
        self.lbrc_connection = dinterface(bus, service, "/connection", interface)
        self._config = {}
        self.config = config()
        self.paths = path()
        try:
            proxy_obj = dbus.SessionBus().get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
            self.notify_interface = dbus.Interface(proxy_obj, "org.freedesktop.Notifications")
            self.notify_interface.GetServerInformation()
        except:
            self.notify_interface = None
        try:
            self.bluecontrol = BlueZControl()
        except:
            self.bluecontrol = None
        self._config["icon_size"] = 24
        self.icon = gtk.gdk.pixbuf_new_from_file(self.paths.get_datafile("LBRC.svg"))
        self.trayicon = egg.trayicon.TrayIcon("LBRC")
        image = gtk.Image()
        image.set_from_pixbuf(
            self.icon.scale_simple(self._config["icon_size"], self._config["icon_size"], gtk.gdk.INTERP_BILINEAR)
        )
        self._create_menu()
        eventbox = gtk.EventBox()
        self.trayicon.add(eventbox)
        eventbox.add(image)
        eventbox.add_events(gtk.gdk.BUTTON_PRESS)
        eventbox.connect("button-press-event", self.popup_menu)
        self.lbrc_core.connect_to_signal("shutdown", lambda: gtk.main_quit())
        self.lbrc_connection.connect_to_signal("connect_cb", self.connect_cb)
        self.lbrc_connection.connect_to_signal("disconnect_cb", self.disconnect_cb)
        self.lbrc_profile.connect_to_signal("profile_changed", self.profile_change_cb)
        self.pid_menu_map[self.lbrc_profile.get_current_profile()].set_active(1)
        self.trayicon.show_all()

        self.config_close_handler = None
Esempio n. 10
0
 def _check_pairing(self, client_address):
     # Check whether we need pairing!
     if not self.config.get_config_item_fb("require-pairing", True):
         self.logger.debug('Pairing not required')
         return True
     self.logger.debug('Check for pairing')
     manager = dinterface(dbus.SystemBus(), 'org.bluez', '/org/bluez', 'org.bluez.Manager')
     adapters = manager.ListAdapters()
     paired = False
     for adapter in adapters:
         adapter = dinterface(dbus.SystemBus(), 'org.bluez', adapter, 'org.bluez.Adapter')
         if adapter.HasBonding(client_address[0]):
             paired = True
             break
         
     if not paired:
         self.logger.debug('We see a new device, that was not yet allowed to connect. Beginning pairing!')
         self.logger.debug('Search for adapter, that reaches the phone')
         for adapter in adapters:
             adapter = dinterface(dbus.SystemBus(), 'org.bluez', adapter, 'org.bluez.Adapter')
             # We asume that an adapter that can resolve the name is the "right" adapter
             try:
                 name = adapter.GetRemoteName(client_address[0])
                 self.logger.debug('Got name %s - will try to create bonding' % (name, ))
                 adapter.CreateBonding(client_address[0])
                 self.logger.debug('Bonding returned')
                 if adapter.HasBonding(client_address[0]):
                     self.logger.debug('Bonding successfull')
                     paired = True
                     self.paired_by_us[client_address[0]] = adapter
                 else:
                     self.logger.debug('Bonding failed')
                 break
             except:
                 self.logger.debug('Exception in BondingCreation (DBUS Methods)')
                 pass
     return paired
Esempio n. 11
0
    def __init__(self, name = "LBRC", serverid = "9c6c8dce-9545-11dc-a3c1-0011d8388a56"):
        """
        @param  serverid:   ID associated to the service we announce
        @type   serverid:   string (hexadecimal)
        @param  name:      The name used to announce the service via bluetooth
        @type   name:      string
        @rtype:     BTServer object
        @return:    BTServer object
        """
        gobject.GObject.__init__(self)
        self.logger = logging.getLogger('LBRC.BTServer')
        self.name = name
        self.serverid = serverid
        self.connectable = 'yes'
        self.filter = {}
        
        self.connected = None
        self.bluetooth_connection = None
        self.bluetooth_keycode = None
        self.config = config()
        self.paired_by_us = {}

        self.client_sock = None
        self.server_sock = None

        self.server_io_watch = None

        self.server_sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
        self.server_sock.bind(("", bluetooth.PORT_ANY))
        (addr, self.port) = self.server_sock.getsockname();
        self.server_sock.listen(1)
        
        self.bluez_db = dinterface(dbus.SystemBus(), 'org.bluez', '/org/bluez', 'org.bluez.Database')
        self.advertise_id = None

        self._register_bluez_signals()
        self._switch_connectable()
Esempio n. 12
0
 def call(self):
     logging.debug("DBUSCall: " + str((self.bus, self.service, self.object, self.interface)))
     iface = dinterface(self.bus, self.service, self.object, self.interface)
     iface.__getattr__(self.method).__call__(*self.arguments)
Esempio n. 13
0
    def _check_pairing(self, client_address):
        """
        Check whether we need to be paired before allowing a connection.
        
        If one is needed and we are not bonded yet, we initiate a pairing
        request.

        @type   self:           BTServer
        @param  self:           The BTServer object responsible for handling 
                                the connection
        @type   client_address: Tuple
        @param  client_address: Client address 
                                incoming connections

        """
        if not self.config.get_config_item_fb("require-pairing", True):
            self.logger.debug('Pairing not required')
            return True
        self.logger.debug('Check for pairing')
        manager = dinterface( dbus.SystemBus(),
                              'org.bluez',
                              '/',
                              'org.bluez.Manager')
        adapters = manager.ListAdapters()
        paired = False
        # TODO: Call a ghost to hunt the designers of api transition of bluez
        #       This is plain evil!
        for i in range(0,len(adapters)):
            if adapters[i].count("/") == 1:
                adapters[i] = "/org/bluez" + adapters[i]
        for adapter in adapters:
            adapter = dinterface(dbus.SystemBus(), 
                                 'org.bluez', 
                                 adapter, 
                                 'org.bluez.Adapter')
            if adapter.HasBonding(client_address[0]):
                paired = True
                break
            
        if not paired:
            self.logger.debug('We see a new device, that was not yet ' + 
                              'allowed to connect. Beginning pairing!')
            self.logger.debug('Search for adapter, that reaches the phone')
            for adapter in adapters:
                adapter = dinterface(dbus.SystemBus(), 
                                     'org.bluez', 
                                     adapter, 
                                     'org.bluez.Adapter')
                # We asume that an adapter that can resolve the name is the 
                # "right" adapter
                try:
                    name = adapter.GetRemoteName(client_address[0])
                    self.logger.debug('Got name %s - will try to create bonding'
                                       % name)
                    adapter.CreateBonding(client_address[0])
                    self.logger.debug('Bonding returned')
                    if adapter.HasBonding(client_address[0]):
                        self.logger.debug('Bonding successfull')
                        paired = True
                        self.paired_by_us[client_address[0]] = adapter
                    else:
                        self.logger.debug('Bonding failed')
                    break
                except dbus.DBusException:
                    self.logger.debug('Exception in BondingCreation' +
                                      ' (DBUS Methods)')
        return paired
Esempio n. 14
0
 def call(self):
     self.logger.debug(str((self.bus, self.service, self.object, self.interface)))
     iface = dinterface(self.bus, self.service, self.object, self.interface)
     iface.__getattr__(self.method).__call__(*self.arguments)