예제 #1
0
 def _on_device_created(self, _adapter, path):
     iter = self.find_device_by_path(path)
     if iter == None:
         dev = Bluez.Device(path)
         dev = Device(dev)
         dev.Temp = True
         self.device_add_event(dev)
예제 #2
0
	def service_connect_handler(self, interface, object_path, method, args, ok, err):
		if interface == "org.bluez.Network" and method == "Connect":
			uuid = args[0]
			name = uuid16_to_name(uuid128_to_uuid16(uuid))
			d = Device(object_path)
			
			conn = self.find_active_connection(d.Address, "panu")
			if conn:
				err(dbus.DBusException(_("Already connected")))
			else:
				params = {}
				params["bluetooth"] = {"name": "bluetooth", "bdaddr":  str(d.Address), "type" : "panu"}
				params["connection"] = {"autoconnect": False, "id": str("%s on %s") % (name, d.Alias), "uuid" : str(uuid1()), "type": "bluetooth"}
				params['ipv4'] = {'addresses': dbus.Array([], dbus.Signature("i")), 'dns': dbus.Array([], dbus.Signature("i")), "method": "auto", "routes": dbus.Array([], dbus.Signature("i"))}		
			
				NewConnectionBuilder(self, params, ok, err)
				
			return True
			
		elif interface == "org.bluez.Network" and method == "Disconnect":
			d = Device(object_path)
			active_conn_path = self.find_active_connection(d.Address, "panu")
			if active_conn_path:
				self.bus.call_blocking("org.freedesktop.NetworkManager", 
						       "/org/freedesktop/NetworkManager", 
						       "org.freedesktop.NetworkManager", 
						       "DeactivateConnection", 
						       "o", 
						       [active_conn_path])
				ok()		       	
				return True
예제 #3
0
	def on_device_created(self, path):
		dprint("created", path)
		iter = self.find_device_by_path(path)
		if iter == None:
			dev = Bluez.Device(path)
			dev = Device(dev)
			dev.Temp = True
			self.device_add_event(dev)
예제 #4
0
 def on_device_created(self, path):
     dprint("created", path)
     iter = self.find_device_by_path(path)
     if iter == None:
         dev = Bluez.Device(path)
         dev = Device(dev)
         dev.Temp = True
         self.device_add_event(dev)
예제 #5
0
    def RefreshServices(self, path, ok, err):
        # BlueZ 4 only!
        device = Device(path)

        def reply(svcs):
            try:
                records = parse_sdp_xml(svcs)
                sdp_save(device.Address, records)
            except:
                pass
            ok()

        device.get_interface().DiscoverServices("", reply_handler=reply, error_handler=err)
예제 #6
0
    def RefreshServices(self, path, ok, err):
        device = Device(path)

        def reply(svcs):
            try:
                records = parse_sdp_xml(svcs)
                sdp_save(device.Address, records)
            except:
                pass
            ok()

        device.GetInterface().DiscoverServices("",
                                               reply_handler=reply,
                                               error_handler=err)
예제 #7
0
파일: NetUsage.py 프로젝트: vis-ram/blueman
    def on_nm_ppp_stats(self, down, up, path):
        if not path in self.nm_paths:
            props = self.bus.call_blocking(
                "org.freedesktop.NetworkManager", path,
                "org.freedesktop.DBus.Properties", "GetAll", "s",
                ["org.freedesktop.NetworkManager.Device"])

            if props["Driver"] == "bluetooth" and "rfcomm" in props[
                    "Interface"]:
                self.nm_paths[path] = True

                portid = int(props["Interface"].strip("rfcomm"))

                ls = rfcomm_list()
                for dev in ls:
                    if dev["id"] == portid:
                        adapter = self.Applet.Manager.get_adapter(dev["src"])
                        device = adapter.find_device(dev["dst"])
                        device = Device(device)

                        self.monitor_interface(NMMonitor, device, path)

                        return
            else:
                self.nm_paths[path] = False
예제 #8
0
    def RemoveDevice(self, device, iter=None, force=False):
        dprint(device)
        if iter == None:
            iter = self.find_device(device)

        if not device.Temp and self.compare(self.selected(), iter):
            self.emit("device-selected", None, None)

        try:
            props = device.GetProperties()
        except:
            self.device_signals.Disconnect(device.get_object_path())
        else:
            if not "Fake" in props:
                self.device_signals.Disconnect(device.GetObjectPath())

        if device.Temp and not force:
            dprint("converting to fake")

            props = copy.deepcopy(props)
            props["Fake"] = True
            dev = FakeDevice(props)

            device = Device(dev)
            self.device_add_event(device)

        else:
            #device.Destroy()
            self.delete(iter)
예제 #9
0
    def connect_service(self, object_path, uuid, ok, err):
        service = Device(object_path).get_service(uuid)

        try:
            self.Applet.Plugins.RecentConns
        except KeyError:
            dprint("RecentConns plugin is unavailable")
        else:
            self.Applet.Plugins.RecentConns.notify(service)

        if service.group == 'serial':
            def reply(rfcomm):
                self.Applet.Plugins.Run("on_rfcomm_connected", service, rfcomm)
                ok(rfcomm)

            rets = self.Applet.Plugins.Run("rfcomm_connect_handler", service, reply, err)
            if True in rets:
                pass
            else:
                dprint("No handler registered")
                err(dbus.DBusException(
                    "Service not supported\nPossibly the plugin that handles this service is not loaded"))
        else:
            def cb(_inst, ret):
                if ret:
                    raise StopException

            if not self.Applet.Plugins.RunEx("service_connect_handler", cb, service, ok, err):
                service.connect(reply_handler=ok, error_handler=err)
예제 #10
0
    def RfcommDisconnect(self, device, rfdevice):
        dev = Device(BluezDevice(device))
        dev.Services["serial"].Disconnect(rfdevice)

        self.Applet.Plugins.Run("on_rfcomm_disconnect", rfdevice)

        dprint("Disonnecting rfcomm device")
예제 #11
0
    def setup_pa(self, device_path, profile):
        device = Device(device_path)

        def load_cb(res):
            dprint("Load result", res)

            if res < 0:
                Notification(
                    _("Bluetooth Audio"),
                    _("Failed to initialize PulseAudio Bluetooth module. Bluetooth audio over PulseAudio will not work."
                      ),
                    pixbuf=get_notification_icon("gtk-dialog-error"),
                    status_icon=self.Applet.Plugins.StatusIcon)
            else:
                Notification(
                    _("Bluetooth Audio"),
                    _("Successfully connected to a Bluetooth audio device. This device will now be available in the PulseAudio mixer"
                      ),
                    pixbuf=get_notification_icon("audio-card"),
                    status_icon=self.Applet.Plugins.StatusIcon)
                if profile == "a2dp":
                    self.setup_pa_sinks(res)

            #connect to other services, so pulseaudio profile switcher could work
            for s in ("headset", "audiosink", "audiosource"):
                try:
                    device.Services[s].Connect()
                except KeyError:
                    pass
                except Exception, e:
                    print e
예제 #12
0
    def on_source_prop_change(self, key, value, device):
        dprint(key, value)

        if key == "State":
            if value == "connected":
                if not device in self.connected_sources:
                    self.connected_sources.append(device)
                    d = Device(device)
                    self.load_module(
                        device,
                        "path=%s address=%s profile=a2dp_source source_properties=device.icon_name=blueman card_properties=device.icon_name=blueman"
                        % (device, d.Address))

            elif value == "disconnected":
                self.try_unload_module(device)
                if device in self.connected_sources:
                    self.connected_sources.remove(device)

            elif value == "playing":
                try:
                    m = self.loaded_modules[device]

                    def on_loaded(m):
                        SourceRedirector(m.id, device, self.pulse_utils)
                        m.disconnect(sig)

                    if not m.id:
                        sig = m.connect("loaded", on_loaded)
                    else:
                        SourceRedirector(m.id, device, self.pulse_utils)

                except Exception, e:
                    dprint(e)
예제 #13
0
    def DisplayKnownDevices(self, autoselect=False):
        self.clear()
        devices = self.Adapter.ListDevices()
        for device in devices:
            self.device_add_event(Device(device))

        if autoselect:
            self.selection.select_path(0)
예제 #14
0
    def on_device_property_changed(self, key, value, path):
        if key == "Connected":
            klass = Device(path).get_properties()["Class"] & 0x1fff

            if klass == 0x504 or klass == 0x508:
                if value:
                    self.xdg_screensaver("suspend")
                else:
                    self.xdg_screensaver("resume")
예제 #15
0
 def get_device(self, item):
     try:
         adapter = self.Applet.Manager.get_adapter(item["adapter"])
     except:
         raise AdapterNotFound
     try:
         return Device(adapter.find_device(item["address"]))
     except:
         raise DeviceNotFound
예제 #16
0
    def DisconnectDevice(self, obj_path, ok, err):
        dev = Device(obj_path)

        self.Applet.Plugins.Run("on_device_disconnect", dev)

        def on_timeout():
            dev.Disconnect(reply_handler=ok, error_handler=err)

        GObject.timeout_add(1000, on_timeout)
예제 #17
0
    def RfcommConnect(self, device, uuid, ok, err):
        def reply(rfcomm):
            self.Applet.Plugins.Run("on_rfcomm_connected", dev, rfcomm, uuid)
            ok(rfcomm)

        dev = Device(device)
        try:
            self.Applet.Plugins.RecentConns.notify(dev.Copy(),
                                                   "org.bluez.Serial", [uuid])
        except KeyError:
            pass

        rets = self.Applet.Plugins.Run("rfcomm_connect_handler", dev, uuid,
                                       reply, err)
        if True in rets:
            pass
        else:
            dprint("No handler registered")
            err(
                dbus.DBusException(
                    "Service not supported\nPossibly the plugin that handles this service is not loaded"
                ))
예제 #18
0
    def disconnect_service(self, object_path, uuid, port, ok, err):
        service = Device(object_path).get_service(uuid)

        if service.group == 'serial':
            service.disconnect(port)

            self.Applet.Plugins.Run("on_rfcomm_disconnect", port)

            dprint("Disonnecting rfcomm device")
        else:

            def cb(_inst, ret):
                if ret:
                    raise StopException

            if not self.Applet.Plugins.RunEx("service_disconnect_handler", cb, service, ok, err):
                service.disconnect(reply_handler=ok, error_handler=err)
예제 #19
0
    def on_device_found(self, address, props):
        if self.discovering:
            dprint("Device discovered", address)

            props["Address"] = address
            props["Fake"] = True
            dev = FakeDevice(props)
            device = Device(dev)

            iter = self.find_device(dev)
            if not iter:
                self.device_add_event(device)
                iter = self.find_device(device)
                self.row_update_event(iter, "RSSI", props["RSSI"])
            else:
                self.row_update_event(iter, "Alias", props["Alias"])

            print("RSSI:", props["RSSI"])
예제 #20
0
    def ServiceProxy(self, interface, object_path, _method, args, ok, err):

        if _method == "Connect":
            dev = Device(object_path)
            try:
                self.Applet.Plugins.RecentConns.notify(dev, interface, args)
            except KeyError:
                dprint("RecentConns plugin is unavailable")

        self.handled = False

        def cb(inst, ret):
            if ret == True:
                self.handled = True
                #stop further execution
                raise StopException

        self.Applet.Plugins.RunEx("service_connect_handler", cb, interface,
                                  object_path, _method, args, ok, err)

        if not self.handled:
            self.ConnectHelper(interface, object_path, _method, args, ok, err)

        del self.handled
예제 #21
0
    def __init__(self, module_id, device_path, pa_utils):
        if module_id in SourceRedirector.instances:
            return
        else:
            SourceRedirector.instances.append(module_id)

        self.module_id = module_id
        self.pa_utils = pa_utils
        self.device = Device(device_path)
        self.signals = SignalTracker()
        self.bus = dbus.SystemBus()
        self.signals.Handle("dbus",
                            self.bus,
                            self.on_source_prop_change,
                            "PropertyChanged",
                            "org.bluez.AudioSource",
                            path=device_path)

        self.pacat = None
        self.parec = None
        self.loopback_id = None

        dprint("Starting source redirector")

        def sources_cb(sources):
            for k, v in sources.iteritems():
                props = v["proplist"]
                if "bluetooth.protocol" in props:
                    if props["bluetooth.protocol"] == "a2dp_source":
                        if v["owner_module"] == self.module_id:
                            dprint("Found source", k)
                            self.start_redirect(k)
                            return
            dprint("Source not found :(")

        self.pa_utils.ListSources(sources_cb)
예제 #22
0
파일: NetUsage.py 프로젝트: vis-ram/blueman
 def on_network_property_changed(self, key, value, path):
     dprint(key, value, path)
     if key == "Interface" and value != "":
         d = BluezDevice(path)
         d = Device(d)
         self.monitor_interface(Monitor, d, value)
예제 #23
0
 def _on_network_property_changed(self, network, key, value):
     if key == "Interface" and value != "":
         d = BluezDevice(network.get_object_path())
         d = Device(d)
         self.monitor_interface(Monitor, d, value)
예제 #24
0
    def _on_authorize(self,
                      _agent,
                      transfer_path,
                      address=None,
                      filename=None,
                      size=None):
        if address and filename and size:
            # stand-alone obexd
            # FIXME: /tmp is only the default. Can we get the actual root
            # directory from stand-alone obexd?
            root = '/tmp'
        else:
            # BlueZ 5 integrated obexd
            transfer = obex.Transfer(transfer_path)
            session = obex.Session(transfer.session)
            root = session.root
            address = session.address
            filename = transfer.name
            size = transfer.size

        try:
            device = Device(
                self._applet.Manager.get_adapter().find_device(address))
            name = device.Alias
            trusted = device.Trusted
        except Exception as e:
            dprint(e)
            name = address
            trusted = False

        self._pending_transfer = {
            'transfer_path': transfer_path,
            'address': address,
            'root': root,
            'filename': filename,
            'size': size,
            'name': name
        }

        try:
            status_icon = self._applet.Plugins.StatusIcon
        except:
            status_icon = None

        # This device was neither allowed nor is it trusted -> ask for confirmation
        if address not in self._allowed_devices and not (
                self._config['opp-accept'] and trusted):
            self._notification = Notification(
                _("Incoming file over Bluetooth"),
                _("Incoming file %(0)s from %(1)s") % {
                    "0": "<b>" + filename + "</b>",
                    "1": "<b>" + name + "</b>"
                },
                30000, [["accept", _("Accept"), "help-about"],
                        ["reject", _("Reject"), "help-about"]],
                self._on_action,
                pixbuf=get_icon("blueman", 48),
                status_icon=status_icon)
        # Device is trusted or was already allowed, larger file -> display a notification, but auto-accept
        elif size > 350000:
            self._notification = Notification(
                _("Receiving file"),
                _("Receiving file %(0)s from %(1)s") % {
                    "0": "<b>" + filename + "</b>",
                    "1": "<b>" + name + "</b>"
                },
                pixbuf=get_icon("blueman", 48),
                status_icon=status_icon)
            self._on_action(self._notification, 'accept')
        # Device is trusted or was already allowed. very small file -> auto-accept and transfer silently
        else:
            self._notification = None
            self._on_action(self._notification, "accept")
예제 #25
0
    def on_transfer_started(self, session, filename, local_path, total_bytes):
        dprint("transfer started", filename)
        info = session.server.GetServerSessionInfo(session.object_path)
        trusted = False
        try:
            dev = self.Applet.Manager.get_adapter().find_device(
                info["BluetoothAddress"])
            dev = Device(dev)
            name = dev.Alias
            trusted = dev.Trusted
        except Exception as e:
            dprint(e)
            name = info["BluetoothAddress"]

        wsession = weakref.proxy(session)
        wself = weakref.proxy(self)

        icon = get_icon("blueman", 48)

        session.transfer["filename"] = filename
        session.transfer["filepath"] = local_path
        session.transfer["total"] = total_bytes
        session.transfer["finished"] = False
        session.transfer["failed"] = False
        session.transfer["waiting"] = True

        session.transfer["address"] = info["BluetoothAddress"]
        session.transfer["name"] = name

        session.transfer["transferred"] = 0

        def access_cb(n, action):
            dprint(action)

            if action == "closed":
                if wsession.transfer["waiting"]:
                    wsession.Reject()

            if wsession.transfer["waiting"]:
                if action == "accept":
                    wsession.Accept()
                    wself.allowed_devices.append(wsession.transfer["address"])
                    GObject.timeout_add(60000, wself.allowed_devices.remove,
                                        wsession.transfer["address"])
                else:
                    wsession.Reject()
                wsession.transfer["waiting"] = False

        if info["BluetoothAddress"] not in self.allowed_devices and not (
                self.Config.props.opp_accept and trusted):

            n = Notification(
                _("Incoming file over Bluetooth"),
                _("Incoming file %(0)s from %(1)s") % {
                    "0": "<b>" + os.path.basename(filename) + "</b>",
                    "1": "<b>" + name + "</b>"
                }, 30000, [["accept", _("Accept"), "help-about"],
                           ["reject", _("Reject"), "help-about"]], access_cb,
                icon, self.status_icon)

            if total_bytes > 350000:
                session.transfer["normal_transfers"] += 1
            else:
                session.transfer["silent_transfers"] += 1
        else:
            if total_bytes > 350000:
                n = Notification(
                    _("Receiving file"),
                    _("Receiving file %(0)s from %(1)s") % {
                        "0": "<b>" + os.path.basename(filename) + "</b>",
                        "1": "<b>" + name + "</b>"
                    },
                    pixbuf=icon,
                    status_icon=self.status_icon)

                session.transfer["normal_transfers"] += 1
            else:
                session.transfer["silent_transfers"] += 1
                n = None

            access_cb(n, "accept")

        session.transfer["notification"] = n
예제 #26
0
 def _on_device_property_changed(self, _device, key, value, path):
     if key == "Connected" and not value:
         self.terminate_all_scripts(Device(path).Address)
예제 #27
0
파일: NetUsage.py 프로젝트: vis-ram/blueman
    def __init__(self, parent):
        if not Dialog.running:
            Dialog.running = True
        else:
            return
        self.config = None
        self.parent = parent
        builder = Gtk.Builder()
        builder.add_from_file(UI_PATH + "/net-usage.ui")
        builder.set_translation_domain("blueman")

        self.dialog = builder.get_object("dialog")
        self.dialog.connect("response", self.on_response)
        cr1 = Gtk.CellRendererText()
        cr1.props.ellipsize = Pango.EllipsizeMode.END

        self.devices = {}
        self.signals = SignalTracker()

        self.signals.Handle(parent, "monitor-added", self.monitor_added)
        self.signals.Handle(parent, "monitor-removed", self.monitor_removed)
        self.signals.Handle(parent, "stats", self.on_stats)

        cr2 = Gtk.CellRendererText()
        cr2.props.sensitive = False
        cr2.props.style = Pango.Style.ITALIC

        self.liststore = Gtk.ListStore(str, str, str, object)

        self.e_ul = builder.get_object("e_ul")
        self.e_dl = builder.get_object("e_dl")
        self.e_total = builder.get_object("e_total")

        self.l_started = builder.get_object("l_started")
        self.l_duration = builder.get_object("l_duration")

        self.b_reset = builder.get_object("b_reset")
        self.b_reset.connect("clicked", self.on_reset)

        self.cb_device = builder.get_object("cb_device")
        self.cb_device.props.model = self.liststore
        self.cb_device.connect("changed", self.on_selection_changed)

        self.cb_device.pack_start(cr1, True)
        self.cb_device.add_attribute(cr1, 'markup', 1)

        self.cb_device.pack_start(cr2, False)
        self.cb_device.add_attribute(cr2, 'markup', 2)

        general_config = Config("org.blueman.general")

        added = False
        for d in general_config["netusage-dev-list"]:
            for m in parent.monitors:
                if d == m.device.Address:
                    iter = self.liststore.append([
                        d,
                        self.get_caption(m.device.Alias, m.device.Address),
                        _("Connected:") + " " + m.interface, m
                    ])
                    if self.cb_device.get_active() == -1:
                        self.cb_device.set_active_iter(iter)
                    added = True
                    break
            if not added:
                name = d
                if self.parent.Applet.Manager:
                    for a in self.parent.Applet.Manager.list_adapters():
                        try:
                            device = a.find_device(d)
                            device = Device(device)
                            name = self.get_caption(device.Alias,
                                                    device.Address)
                        except:
                            pass

                self.liststore.append([d, name, _("Not Connected"), None])
            added = False
        if len(self.liststore) > 0:
            if self.cb_device.get_active() == -1:
                self.cb_device.set_active(0)
        else:
            d = Gtk.MessageDialog(
                parent=self.dialog,
                flags=Gtk.DialogFlags.MODAL,
                type=Gtk.MessageType.INFO,
                buttons=Gtk.ButtonsType.CLOSE,
                message_format=
                _("No usage statistics are available yet. Try establishing a connection first and then check this page."
                  ))
            d.props.icon_name = "blueman"
            d.run()
            d.destroy()
            self.on_response(None, None)
            return

        self.dialog.show()