コード例 #1
0
class NetworkService(Service):
    def __init__(self, device, uuid):
        super().__init__(device, uuid)
        self._service = Network(device.get_object_path())

    @property
    def available(self):
        # This interface is only available after pairing
        return self.device["Paired"]

    @property
    def connected(self):
        if not self.available:
            return False

        return self._service['Connected']

    def connect(self, reply_handler=None, error_handler=None):
        self._service.connect(self.uuid,
                              reply_handler=reply_handler,
                              error_handler=error_handler)

    def disconnect(self, reply_handler=None, error_handler=None, *args):
        self._service.disconnect(reply_handler=reply_handler,
                                 error_handler=error_handler)
コード例 #2
0
ファイル: NMPANSupport.py プロジェクト: bwRavencl/blueman
    def service_connect_handler(self, interface, object_path, method, args, ok, err):
        if interface == Network().get_interface_name() 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 == Network().get_interface_name() 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
class NetworkService(Service):
    def __init__(self, device: Device, uuid: str):
        super().__init__(device, uuid)
        self._service = Network(device.get_object_path())

    @property
    def available(self) -> bool:
        # This interface is only available after pairing
        paired: bool = self.device["Paired"]
        return paired

    @property
    def connected(self) -> bool:
        if not self.available:
            return False

        connected: bool = self._service["Connected"]
        return connected

    def connect(
        self,
        reply_handler: Optional[Callable[[str], None]] = None,
        error_handler: Optional[Callable[[BluezDBusException], None]] = None,
    ) -> None:
        self._service.connect(self.uuid, reply_handler=reply_handler, error_handler=error_handler)

    def disconnect(
        self,
        reply_handler: Optional[Callable[[], None]] = None,
        error_handler: Optional[Callable[[BluezDBusException], None]] = None,
    ) -> None:
        self._service.disconnect(reply_handler=reply_handler, error_handler=error_handler)
コード例 #4
0
ファイル: DhcpClient.py プロジェクト: DavidGriffith/blueman
class DhcpClient(AppletPlugin):
    __description__ = _("Provides a basic dhcp client for Bluetooth PAN connections.")
    __icon__ = "network"
    __author__ = "Walmis"

    _any_network = None

    def on_load(self, applet):
        self._any_network = Network()
        self._any_network.connect_signal('property-changed', self._on_network_prop_changed)

        self.quering = []

    def on_unload(self):
        del self._any_network

    @dbus.service.method('org.blueman.Applet', in_signature="s")
    def DhcpClient(self, interface):
        self.dhcp_acquire(interface)

    def _on_network_prop_changed(self, _network, key, value):
        if key == "Interface":
            if value != "":
                self.dhcp_acquire(value)

    def dhcp_acquire(self, device):
        if device not in self.quering:
            self.quering.append(device)
        else:
            return

        if device != "":
            def reply(ip_address):
                Notification(_("Bluetooth Network"),
                             _("Interface %(0)s bound to IP address %(1)s") % {"0": device, "1": ip_address},
                             pixbuf=get_icon("network-workgroup", 48),
                             status_icon=self.Applet.Plugins.StatusIcon)

                self.quering.remove(device)

            def err(msg):
                dprint(msg)
                Notification(_("Bluetooth Network"), _("Failed to obtain an IP address on %s") % (device),
                             pixbuf=get_icon("network-workgroup", 48),
                             status_icon=self.Applet.Plugins.StatusIcon)

                self.quering.remove(device)

            Notification(_("Bluetooth Network"), _("Trying to obtain an IP address on %s\nPlease wait..." % device),
                         pixbuf=get_icon("network-workgroup", 48),
                         status_icon=self.Applet.Plugins.StatusIcon)

            m = Mechanism()
            m.DhcpClient(device, reply_handler=reply, error_handler=err, timeout=120)
コード例 #5
0
ファイル: NetUsage.py プロジェクト: vis-ram/blueman
    def on_load(self, applet):
        GObject.GObject.__init__(self)
        self.monitors = []
        self.devices = weakref.WeakValueDictionary()
        self.signals = SignalTracker()

        bus = self.bus = dbus.SystemBus()
        self.signals.Handle('bluez',
                            Network(),
                            self.on_network_property_changed,
                            'PropertyChanged',
                            path_keyword="path")

        item = create_menuitem(_("Network _Usage"),
                               get_icon("network-wireless", 16))
        item.props.tooltip_text = _("Shows network traffic usage")
        self.signals.Handle(item, "activate", self.activate_ui)
        self.Applet.Plugins.Menu.Register(self, item, 84, True)

        self.signals.Handle("dbus",
                            bus,
                            self.on_nm_ppp_stats,
                            "PppStats",
                            "org.freedesktop.NetworkManager.Device.Serial",
                            path_keyword="path")
        self.nm_paths = {}
コード例 #6
0
    def on_load(self, applet):
        self.Signals = SignalTracker()

        self.Signals.Handle('bluez',
                            Network(),
                            self.on_network_prop_changed,
                            'PropertyChanged',
                            path_keyword='path')
コード例 #7
0
class NetworkService(Service):
    def __init__(self, device: Device, uuid: str):
        super().__init__(device, uuid)
        self._service = Network(obj_path=device.get_object_path())

    @property
    def available(self) -> bool:
        # This interface is only available after pairing
        paired: bool = self.device["Paired"]
        return paired

    @property
    def connectable(self) -> bool:
        return not self.available or not self._service["Connected"]

    @property
    def connected_instances(self) -> List[Instance]:
        return [] if self.connectable else [Instance(self.name)]

    def connect(
        self,
        reply_handler: Optional[Callable[[str], None]] = None,
        error_handler: Optional[Callable[[BluezDBusException], None]] = None,
    ) -> None:
        self._service.connect(self.uuid,
                              reply_handler=reply_handler,
                              error_handler=error_handler)

    def disconnect(
        self,
        reply_handler: Optional[Callable[[], None]] = None,
        error_handler: Optional[Callable[[BluezDBusException], None]] = None,
    ) -> None:
        self._service.disconnect(reply_handler=reply_handler,
                                 error_handler=error_handler)

    @property
    def common_actions(self) -> Set[Action]:
        def renew() -> None:
            AppletService().DhcpClient('(s)', self.device.get_object_path())

        return {
            Action(_("Renew IP Address"), "view-refresh", {"DhcpClient"},
                   renew)
        }
コード例 #8
0
class NetworkService(Service):
    def __init__(self, device, uuid):
        super(NetworkService, self).__init__(device, uuid)
        self._service = Network(device.get_object_path())

    @property
    def connected(self):
        try:
            return self._service.get_properties()['Connected']
        except BluezDBusException as e:
            dprint('Could not get properties of network service: %s' % e)
            return False

    def connect(self, reply_handler=None, error_handler=None):
        self._service.connect(self.uuid, reply_handler=reply_handler, error_handler=error_handler)

    def disconnect(self, reply_handler=None, error_handler=None, *args):
        self._service.disconnect(reply_handler=reply_handler, error_handler=error_handler)
コード例 #9
0
class NetworkService(Service):
    def __init__(self, device, uuid):
        super(NetworkService, self).__init__(device, uuid)
        self._service = Network(device.get_object_path())

    @property
    def connected(self):
        try:
            return self._service.get_properties()['Connected']
        except DBusException as e:
            dprint('Could not get properties of network service: %s' % e)
            return False

    def connect(self, reply_handler=None, error_handler=None):
        self._service.connect(self.uuid, reply_handler=reply_handler, error_handler=error_handler)

    def disconnect(self, reply_handler=None, error_handler=None, *args):
        self._service.disconnect(reply_handler=reply_handler, error_handler=error_handler)
コード例 #10
0
ファイル: RecentConns.py プロジェクト: bwRavencl/blueman
    def add_item(self, item):
        device = item["device"]

        if item["service"] == Serial().get_interface_name():
            name = sdp.sdp_get_serial_name(item["address"],
                                           item["conn_args"][0])

        elif item["service"] == Network().get_interface_name():
            name = _("Network Access (%s)") % sdp.uuid16_to_name(
                sdp.uuid128_to_uuid16(item["conn_args"][0]))
        else:
            try:
                name = sdp.bluez_to_friendly_name(
                    item["service"].split(".")[-1].lower())
            except:
                name = item["service"].split(".")[-1] + " " + _("Service")
                name = name.capitalize()

        if not item["mitem"]:
            mitem = create_menuitem("", get_icon(item["icon"], 16))
            item["mitem"] = mitem
            mitem.connect("activate", self.on_item_activated, item)
        else:
            mitem = item["mitem"]
            mitem.props.sensitive = True
            mitem.props.tooltip_text = None

        item["mitem"].props.label = (_("%(service)s on %(device)s") % {
            "service": name,
            "device": item["alias"]
        })

        if item["adapter"] not in self.Adapters.values():
            if item["device"] and item["gsignal"]:
                item["device"].disconnect(item["gsignal"])

            item["device"] = None
        elif not item["device"] and item["adapter"] in self.Adapters.values():
            try:
                dev = self.get_device(item)
                item["device"] = dev
                item["gsignal"] = item["device"].connect(
                    "invalidated", self.on_device_removed, item)

            except:
                RecentConns.items.remove(item)
                self.initialize()

        if not item["device"]:
            mitem.props.sensitive = False
            mitem.props.tooltip_text = _(
                "Adapter for this connection is not available")

        self.prepend(mitem)
        mitem.show()
コード例 #11
0
ファイル: ManagerDeviceMenu.py プロジェクト: die-uhus/blueman
    def __init__(self, blueman):
        GObject.GObject.__init__(self)
        self.Blueman = blueman
        self.SelectedDevice = None

        self.is_popup = False

        self._device_property_changed_signal = self.Blueman.List.connect("device-property-changed",
                                                                         self.on_device_property_changed)
        self._selection_done_signal = None

        ManagerDeviceMenu.__instances__.append(self)

        self._any_network = Network()
        self._any_network.connect_signal('property-changed', self._on_service_property_changed)

        self._any_device = Device()
        self._any_device.connect_signal('property-changed', self._on_service_property_changed)

        self.Generate()
コード例 #12
0
    def on_load(self, applet):
        self.Signals = SignalTracker()

        self.add_dbus_method(self.DhcpClient, in_signature="s")

        self.Signals.Handle('bluez',
                            Network(),
                            self.on_network_prop_changed,
                            'PropertyChanged',
                            path_keyword="path")

        self.quering = []
コード例 #13
0
class NetworkService(Service):
    def __init__(self, device, uuid):
        super(NetworkService, self).__init__(device, uuid)
        self._service = Network(device.get_object_path())

    @property
    def available(self):
        # This interface is only available after pairing
        return self.device["Paired"]

    @property
    def connected(self):
        if not self.available:
            return False

        return self._service['Connected']

    def connect(self, reply_handler=None, error_handler=None):
        self._service.connect(self.uuid, reply_handler=reply_handler, error_handler=error_handler)

    def disconnect(self, reply_handler=None, error_handler=None, *args):
        self._service.disconnect(reply_handler=reply_handler, error_handler=error_handler)
コード例 #14
0
ファイル: NetUsage.py プロジェクト: zjsxwc/blueman
    def on_load(self, applet):
        GObject.GObject.__init__(self)
        self.monitors = []
        self.devices = weakref.WeakValueDictionary()

        self.bus = dbus.SystemBus()

        self._any_network = Network()
        self._any_network.connect_signal('property-changed',
                                         self._on_network_property_changed)

        item = create_menuitem(_("Network _Usage"),
                               get_icon("network-wireless", 16))
        item.props.tooltip_text = _("Shows network traffic usage")
        item.connect("activate", self.activate_ui)
        self.Applet.Plugins.Menu.Register(self, item, 84, True)

        self.bus.add_signal_receiver(
            self.on_nm_ppp_stats,
            "PppStats",
            "org.freedesktop.NetworkManager.Device.Serial",
            path_keyword="path")
        self.nm_paths = {}
コード例 #15
0
ファイル: NetUsage.py プロジェクト: KunLiu1210/blueman
    def on_load(self, applet):
        GObject.GObject.__init__(self)
        self.monitors = []
        self.devices = weakref.WeakValueDictionary()

        self.bus = dbus.SystemBus()

        self._any_network = Network()
        self._any_network.connect_signal('property-changed', self._on_network_property_changed)

        item = create_menuitem(_("Network _Usage"), get_icon("network-wireless", 16))
        item.props.tooltip_text = _("Shows network traffic usage")
        item.connect("activate", self.activate_ui)
        self.Applet.Plugins.Menu.Register(self, item, 84, True)

        self.bus.add_signal_receiver(self.on_nm_ppp_stats, "PppStats", "org.freedesktop.NetworkManager.Device.Serial",
                                     path_keyword="path")
        self.nm_paths = {}
コード例 #16
0
ファイル: DhcpClient.py プロジェクト: blueman-project/blueman
    def dhcp_acquire(self, object_path: str) -> None:
        device = Network(obj_path=object_path)["Interface"]

        if device not in self.quering:
            self.quering.append(device)
        else:
            return

        if device != "":

            def reply(_obj: Mechanism, result: str, _user_data: None) -> None:
                logging.info(result)
                Notification(_("Bluetooth Network"),
                             _("Interface %(0)s bound to IP address %(1)s") % {
                                 "0": device,
                                 "1": result
                             },
                             icon_name="network-workgroup").show()

                self.quering.remove(device)

            def err(_obj: Mechanism, result: GLib.Error,
                    _user_data: None) -> None:
                logging.warning(result)
                Notification(_("Bluetooth Network"),
                             _("Failed to obtain an IP address on %s") %
                             device,
                             icon_name="network-workgroup").show()

                self.quering.remove(device)

            Notification(
                _("Bluetooth Network"),
                _("Trying to obtain an IP address on %s\nPlease wait…" %
                  device),
                icon_name="network-workgroup").show()

            m = Mechanism()
            m.DhcpClient('(s)',
                         object_path,
                         result_handler=reply,
                         error_handler=err,
                         timeout=120 * 1000)
コード例 #17
0
ファイル: ManagerDeviceMenu.py プロジェクト: smcv/blueman
    def __init__(self, blueman):
        GObject.GObject.__init__(self)
        self.Blueman = blueman
        self.SelectedDevice = None

        self.is_popup = False

        self._device_property_changed_signal = self.Blueman.List.connect("device-property-changed",
                                                                         self.on_device_property_changed)
        self._selection_done_signal = None

        ManagerDeviceMenu.__instances__.append(self)

        self._any_network = Network()
        self._any_network.connect_signal('property-changed', self._on_service_property_changed)

        self._any_device = Device()
        self._any_device.connect_signal('property-changed', self._on_service_property_changed)

        self.Generate()
コード例 #18
0
class ManagerDeviceMenu(Gtk.Menu):
    __ops__ = {}
    __instances__ = []

    def __init__(self, blueman):
        GObject.GObject.__init__(self)
        self.Blueman = blueman
        self.SelectedDevice = None

        self.is_popup = False

        self._device_property_changed_signal = self.Blueman.List.connect(
            "device-property-changed", self.on_device_property_changed)
        self._selection_done_signal = None

        ManagerDeviceMenu.__instances__.append(self)

        self._any_network = Network()
        self._any_network.connect_signal('property-changed',
                                         self._on_service_property_changed)

        self._any_device = Device()
        self._any_device.connect_signal('property-changed',
                                        self._on_service_property_changed)

        self.Generate()

    def __del__(self):
        dprint("deleting devicemenu")

    def popup(self, *args):
        self.is_popup = True

        if not self._device_property_changed_signal:
            self._device_property_changed_signal = self.Blueman.List.connect(
                "device-property-changed", self.on_device_property_changed)

        if not self._selection_done_signal:

            def disconnectall(x):
                self.disconnect(self._device_property_changed_signal)
                self.disconnect(self._selection_done_signal)

            self._selection_done_signal = self.connect("selection-done",
                                                       disconnectall)

        self.Generate()

        Gtk.Menu.popup(self, *args)

    def clear(self):
        def each(child, data):
            self.remove(child)
            child.destroy()

        self.foreach(each, None)

    def set_op(self, device, message):
        ManagerDeviceMenu.__ops__[device.get_object_path()] = message
        for inst in ManagerDeviceMenu.__instances__:
            dprint("op: regenerating instance", inst)
            if inst.SelectedDevice == self.SelectedDevice and not (
                    inst.is_popup and not inst.props.visible):
                inst.Generate()

    def get_op(self, device):
        try:
            return ManagerDeviceMenu.__ops__[device.get_object_path()]
        except:
            return None

    def unset_op(self, device):
        del ManagerDeviceMenu.__ops__[device.get_object_path()]
        for inst in ManagerDeviceMenu.__instances__:
            dprint("op: regenerating instance", inst)
            if inst.SelectedDevice == self.SelectedDevice and not (
                    inst.is_popup and not inst.props.visible):
                inst.Generate()

    def _on_service_property_changed(self, _service, key, _value, _path):
        if key == "Connected":
            self.Generate()

    def on_connect(self, _item, service):
        device = service.device

        def success(*args2):
            dprint("success", args2)
            prog.message(_("Success!"))

            if isinstance(service, SerialPort
                          ) and SERIAL_PORT_SVCLASS_ID == uuid128_to_uuid16(
                              service.uuid):
                MessageArea.show_message(
                    _("Serial port connected to %s") % args2[0],
                    "dialog-information")
            else:
                MessageArea.close()

            self.unset_op(device)

        def fail(*args):
            prog.message(_("Failed"))

            self.unset_op(device)
            dprint("fail", args)
            MessageArea.show_message(
                _("Connection Failed: ") + e_(str(args[0])))

        self.set_op(device, _("Connecting..."))
        prog = ManagerProgressbar(self.Blueman, False)

        try:
            appl = AppletService()
        except:
            dprint("** Failed to connect to applet")
            fail()
            return
        try:
            appl.SetTimeHint(Gtk.get_current_event_time())
        except:
            pass

        appl.connect_service(device.get_object_path(),
                             service.uuid,
                             reply_handler=success,
                             error_handler=fail,
                             timeout=200)

        prog.start()

    def on_disconnect(self, item, service, port=0):
        try:
            appl = AppletService()
        except:
            dprint("** Failed to connect to applet")
            return

        appl.disconnect_service(service.device.get_object_path(), service.uuid,
                                port)
        self.Generate()

    def on_device_property_changed(self, List, device, iter, key_value):
        key, value = key_value
        # print "menu:", key, value
        if List.compare(iter, List.selected()):
            if key == "Connected" \
                or key == "UUIDs" \
                or key == "Trusted" \
                or key == "Paired":
                self.Generate()

    def Generate(self):
        self.clear()

        appl = AppletService()

        items = []

        if not self.is_popup or self.props.visible:
            selected = self.Blueman.List.selected()
            if not selected:
                return
            device = self.Blueman.List.get(selected, "device")["device"]
        else:
            (x, y) = self.Blueman.List.get_pointer()
            path = self.Blueman.List.get_path_at_pos(x, y)
            if path != None:
                device = self.Blueman.List.get(path[0], "device")["device"]
            else:
                return

        if not device.Valid:
            return
        self.SelectedDevice = device

        op = self.get_op(device)

        if op != None:
            item = create_menuitem(op, get_icon("network-transmit-recieve",
                                                16))
            item.props.sensitive = False
            item.show()
            self.append(item)
            return

        rets = self.Blueman.Plugins.Run("on_request_menu_items", self, device)

        for ret in rets:
            if ret:
                for (item, pos) in ret:
                    items.append((pos, item))

        dprint(device.Alias)

        have_disconnectables = False
        have_connectables = False

        if True in map(lambda x: x[0] >= 100 and x[0] < 200, items):
            have_disconnectables = True

        if True in map(lambda x: x[0] < 100, items):
            have_connectables = True

        if True in map(lambda x: x[0] >= 200,
                       items) and (have_connectables or have_disconnectables):
            item = Gtk.SeparatorMenuItem()
            item.show()
            items.append((199, item))

        if have_connectables:
            item = Gtk.MenuItem()
            label = Gtk.Label()
            label.set_markup(_("<b>Connect To:</b>"))
            label.props.xalign = 0.0

            label.show()
            item.add(label)
            item.props.sensitive = False
            item.show()
            items.append((0, item))

        if have_disconnectables:
            item = Gtk.MenuItem()
            label = Gtk.Label()
            label.set_markup(_("<b>Disconnect:</b>"))
            label.props.xalign = 0.0

            label.show()
            item.add(label)
            item.props.sensitive = False
            item.show()
            items.append((99, item))

        items.sort(key=itemgetter(0))
        for priority, item in items:
            self.append(item)

        if items != []:
            item = Gtk.SeparatorMenuItem()
            item.show()
            self.append(item)

        del items

        send_item = create_menuitem(_("Send a _File..."),
                                    get_icon("edit-copy", 16))
        send_item.props.sensitive = False
        self.append(send_item)
        send_item.show()

        uuids = device.UUIDs
        for uuid in uuids:
            uuid16 = uuid128_to_uuid16(uuid)
            if uuid16 == OBEX_OBJPUSH_SVCLASS_ID:
                send_item.connect("activate",
                                  lambda x: self.Blueman.send(device))
                send_item.props.sensitive = True

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Pair"), get_icon("dialog-password", 16))
        item.props.tooltip_text = _("Create pairing with the device")
        self.append(item)
        item.show()
        if not device.Paired:
            item.connect("activate", lambda x: self.Blueman.bond(device))
        else:
            item.props.sensitive = False

        if not device.Trusted:
            item = create_menuitem(_("_Trust"), get_icon("blueman-trust", 16))
            item.connect("activate",
                         lambda x: self.Blueman.toggle_trust(device))
            self.append(item)
            item.show()
        else:
            item = create_menuitem(_("_Untrust"),
                                   get_icon("blueman-untrust", 16))
            self.append(item)
            item.connect("activate",
                         lambda x: self.Blueman.toggle_trust(device))
            item.show()
        item.props.tooltip_text = _("Mark/Unmark this device as trusted")

        item = create_menuitem(_("_Setup..."),
                               get_icon("document-properties", 16))
        self.append(item)
        item.connect("activate", lambda x: self.Blueman.setup(device))
        item.show()
        item.props.tooltip_text = _("Run the setup assistant for this device")

        def on_rename(_item, device):
            def on_response(dialog, response_id):
                if response_id == Gtk.ResponseType.ACCEPT:
                    device.set('Alias', alias_entry.get_text())
                elif response_id == 1:
                    device.set('Alias', '')
                dialog.destroy()

            builder = Gtk.Builder()
            builder.set_translation_domain("blueman")
            bind_textdomain_codeset("blueman", "UTF-8")
            builder.add_from_file(UI_PATH + "/rename-device.ui")
            dialog = builder.get_object("dialog")
            dialog.set_transient_for(self.Blueman.window)
            dialog.props.icon_name = "blueman"
            alias_entry = builder.get_object("alias_entry")
            alias_entry.set_text(device.Alias)
            dialog.connect("response", on_response)
            dialog.present()

        item = Gtk.MenuItem.new_with_label("Rename device...")
        item.connect('activate', on_rename, device)
        self.append(item)
        item.show()

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Remove..."), get_icon("edit-delete", 16))
        item.connect("activate", lambda x: self.Blueman.remove(device))
        self.append(item)
        item.show()
        item.props.tooltip_text = _(
            "Remove this device from the known devices list")

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Disconnect"),
                               get_icon("network-offline", 16))
        item.props.tooltip_text = _("Forcefully disconnect the device")

        self.append(item)
        item.show()

        def on_disconnect(item):
            def finished(*args):
                self.unset_op(device)

            self.set_op(device, _("Disconnecting..."))
            self.Blueman.disconnect(device,
                                    reply_handler=finished,
                                    error_handler=finished)

        if device.Connected:
            item.connect("activate", on_disconnect)

        else:
            item.props.sensitive = False
コード例 #19
0
ファイル: NetUsage.py プロジェクト: zjsxwc/blueman
class NetUsage(AppletPlugin, GObject.GObject):
    __depends__ = ["Menu"]
    __icon__ = "network-wireless"
    __description__ = _(
        "Allows you to monitor your (mobile broadband) network traffic usage. Useful for limited data access plans. This plugin tracks every device seperately."
    )
    __author__ = "Walmis"
    __autoload__ = False
    __gsignals__ = {
        str('monitor-added'):
        (GObject.SignalFlags.NO_HOOKS, None, (GObject.TYPE_PYOBJECT, )),
        str('monitor-removed'):
        (GObject.SignalFlags.NO_HOOKS, None, (GObject.TYPE_PYOBJECT, )),
        #monitor, tx, rx
        str('stats'): (GObject.SignalFlags.NO_HOOKS, None, (
            GObject.TYPE_PYOBJECT,
            GObject.TYPE_PYOBJECT,
            GObject.TYPE_PYOBJECT,
        )),
    }

    _any_network = None

    def on_load(self, applet):
        GObject.GObject.__init__(self)
        self.monitors = []
        self.devices = weakref.WeakValueDictionary()

        self.bus = dbus.SystemBus()

        self._any_network = Network()
        self._any_network.connect_signal('property-changed',
                                         self._on_network_property_changed)

        item = create_menuitem(_("Network _Usage"),
                               get_icon("network-wireless", 16))
        item.props.tooltip_text = _("Shows network traffic usage")
        item.connect("activate", self.activate_ui)
        self.Applet.Plugins.Menu.Register(self, item, 84, True)

        self.bus.add_signal_receiver(
            self.on_nm_ppp_stats,
            "PppStats",
            "org.freedesktop.NetworkManager.Device.Serial",
            path_keyword="path")
        self.nm_paths = {}

    def on_nm_ppp_stats(self, down, up, path):
        if path not 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"])

                        self.monitor_interface(NMMonitor, device, path)

                        return
            else:
                self.nm_paths[path] = False

    def _on_network_property_changed(self, _network, key, value, path):
        if key == "Interface" and value != "":
            d = Device(path)
            self.monitor_interface(Monitor, d, value)

    def activate_ui(self, item):
        Dialog(self)

    def on_unload(self):
        self.bus.remove_signal_receiver(
            self.on_nm_ppp_stats,
            "PppStats",
            "org.freedesktop.NetworkManager.Device.Serial",
            path_keyword="path")
        del self._any_network
        self.Applet.Plugins.Menu.Unregister(self)

    def monitor_interface(self, montype, *args):
        m = montype(*args)
        self.monitors.append(m)
        m.connect("stats", self.on_stats)
        m.connect("disconnected", self.on_monitor_disconnected)
        self.emit("monitor-added", m)

    def on_ppp_connected(self, device, rfcomm, ppp_port):
        self.monitor_interface(Monitor, device, ppp_port)

    def on_monitor_disconnected(self, monitor):
        self.monitors.remove(monitor)
        self.emit("monitor-removed", monitor)

    def on_stats(self, monitor, tx, rx):
        self.emit("stats", monitor, tx, rx)
コード例 #20
0
ファイル: Services.py プロジェクト: chenjunwen410/blueman
 def renew(_item: Gtk.MenuItem) -> None:
     appl.DhcpClient('(s)', Network(device.get_object_path())["Interface"])
コード例 #21
0
ファイル: NetworkService.py プロジェクト: latot/blueman
 def __init__(self, device, uuid):
     super(NetworkService, self).__init__(device, uuid)
     self._service = Network(device.get_object_path())
コード例 #22
0
class ManagerDeviceMenu(Gtk.Menu):
    __ops__ = {}
    __instances__ = []

    def __init__(self, blueman):
        Gtk.Menu.__init__(self)
        self.set_name("ManagerDeviceMenu")
        self.Blueman = blueman
        self.SelectedDevice = None

        self.is_popup = False

        self._device_property_changed_signal = self.Blueman.List.connect("device-property-changed",
                                                                         self.on_device_property_changed)
        self._selection_done_signal = None

        ManagerDeviceMenu.__instances__.append(self)

        self._any_network = Network()
        self._any_network.connect_signal('property-changed', self._on_service_property_changed)

        self._any_device = Device()
        self._any_device.connect_signal('property-changed', self._on_service_property_changed)

        self.Generate()

    def __del__(self):
        dprint("deleting devicemenu")

    def popup(self, *args):
        self.is_popup = True

        if not self._device_property_changed_signal:
            self._device_property_changed_signal = self.Blueman.List.connect("device-property-changed",
                                                                             self.on_device_property_changed)


        if not self._selection_done_signal:
            def disconnectall(x):
                self.disconnect(self._device_property_changed_signal)
                self.disconnect(self._selection_done_signal)

            self._selection_done_signal = self.connect("selection-done", disconnectall)

        self.Generate()

        Gtk.Menu.popup(self, *args)

    def clear(self):
        def each(child, data):
            self.remove(child)
            child.destroy()

        self.foreach(each, None)

    def set_op(self, device, message):
        ManagerDeviceMenu.__ops__[device.get_object_path()] = message
        for inst in ManagerDeviceMenu.__instances__:
            dprint("op: regenerating instance", inst)
            if inst.SelectedDevice == self.SelectedDevice and not (inst.is_popup and not inst.props.visible):
                inst.Generate()


    def get_op(self, device):
        try:
            return ManagerDeviceMenu.__ops__[device.get_object_path()]
        except:
            return None

    def unset_op(self, device):
        del ManagerDeviceMenu.__ops__[device.get_object_path()]
        for inst in ManagerDeviceMenu.__instances__:
            dprint("op: regenerating instance", inst)
            if inst.SelectedDevice == self.SelectedDevice and not (inst.is_popup and not inst.props.visible):
                inst.Generate()

    def _on_service_property_changed(self, _service, key, _value, _path):
        if key == "Connected":
            self.Generate()

    def on_connect(self, _item, service):
        device = service.device

        def success(*args2):
            dprint("success", " ".join(args2))
            prog.message(_("Success!"))

            if isinstance(service, SerialPort) and SERIAL_PORT_SVCLASS_ID == uuid128_to_uuid16(service.uuid):
                MessageArea.show_message(_("Serial port connected to %s") % args2[0], "dialog-information")
            else:
                MessageArea.close()

            self.unset_op(device)

        def fail(*args):
            prog.message(_("Failed"))

            self.unset_op(device)
            dprint("fail", args)
            MessageArea.show_message(_("Connection Failed: ") + e_(str(args[0])))

        self.set_op(device, _("Connecting..."))
        prog = ManagerProgressbar(self.Blueman, False)

        try:
            appl = AppletService()
        except:
            dprint("** Failed to connect to applet")
            fail()
            return
        try:
            appl.SetTimeHint(Gtk.get_current_event_time())
        except:
            pass

        appl.connect_service(device.get_object_path(), service.uuid,
                             reply_handler=success, error_handler=fail,
                             timeout=200)

        prog.start()

    def on_disconnect(self, item, service, port=0):
        try:
            appl = AppletService()
        except:
            dprint("** Failed to connect to applet")
            return

        appl.disconnect_service(service.device.get_object_path(), service.uuid, port)
        self.Generate()


    def on_device_property_changed(self, List, device, iter, key_value):
        key, value = key_value
        # print "menu:", key, value
        if List.compare(iter, List.selected()):
            if key == "Connected" \
                or key == "UUIDs" \
                or key == "Trusted" \
                or key == "Paired":
                self.Generate()

    def Generate(self):
        self.clear()

        appl = AppletService()

        items = []

        if not self.is_popup or self.props.visible:
            selected = self.Blueman.List.selected()
            if not selected:
                return
            device = self.Blueman.List.get(selected, "device")["device"]
        else:
            (x, y) = self.Blueman.List.get_pointer()
            path = self.Blueman.List.get_path_at_pos(x, y)
            if path != None:
                device = self.Blueman.List.get(path[0], "device")["device"]
            else:
                return

        if not device.Valid:
            return
        self.SelectedDevice = device

        op = self.get_op(device)

        if op != None:
            item = create_menuitem(op, get_icon("network-transmit-recieve", 16))
            item.props.sensitive = False
            item.show()
            self.append(item)
            return

        rets = self.Blueman.Plugins.Run("on_request_menu_items", self, device)

        for ret in rets:
            if ret:
                for (item, pos) in ret:
                    items.append((pos, item))

        dprint(device.Alias)

        have_disconnectables = False
        have_connectables = False

        if True in map(lambda x: x[0] >= 100 and x[0] < 200, items):
            have_disconnectables = True

        if True in map(lambda x: x[0] < 100, items):
            have_connectables = True

        if True in map(lambda x: x[0] >= 200, items) and (have_connectables or have_disconnectables):
            item = Gtk.SeparatorMenuItem()
            item.show()
            items.append((199, item))

        if have_connectables:
            item = Gtk.MenuItem()
            label = Gtk.Label()
            label.set_markup(_("<b>Connect To:</b>"))
            label.props.xalign = 0.0

            label.show()
            item.add(label)
            item.props.sensitive = False
            item.show()
            items.append((0, item))

        if have_disconnectables:
            item = Gtk.MenuItem()
            label = Gtk.Label()
            label.set_markup(_("<b>Disconnect:</b>"))
            label.props.xalign = 0.0

            label.show()
            item.add(label)
            item.props.sensitive = False
            item.show()
            items.append((99, item))

        items.sort(key=itemgetter(0))
        for priority, item in items:
            self.append(item)

        if items != []:
            item = Gtk.SeparatorMenuItem()
            item.show()
            self.append(item)

        del items

        send_item = create_menuitem(_("Send a _File..."), get_icon("edit-copy", 16))
        send_item.props.sensitive = False
        self.append(send_item)
        send_item.show()

        uuids = device.UUIDs
        for uuid in uuids:
            uuid16 = uuid128_to_uuid16(uuid)
            if uuid16 == OBEX_OBJPUSH_SVCLASS_ID:
                send_item.connect("activate", lambda x: self.Blueman.send(device))
                send_item.props.sensitive = True

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Pair"), get_icon("dialog-password", 16))
        item.props.tooltip_text = _("Create pairing with the device")
        self.append(item)
        item.show()
        if not device.Paired:
            item.connect("activate", lambda x: self.Blueman.bond(device))
        else:
            item.props.sensitive = False

        if not device.Trusted:
            item = create_menuitem(_("_Trust"), get_icon("blueman-trust", 16))
            item.connect("activate", lambda x: self.Blueman.toggle_trust(device))
            self.append(item)
            item.show()
        else:
            item = create_menuitem(_("_Untrust"), get_icon("blueman-untrust", 16))
            self.append(item)
            item.connect("activate", lambda x: self.Blueman.toggle_trust(device))
            item.show()
        item.props.tooltip_text = _("Mark/Unmark this device as trusted")

        item = create_menuitem(_("_Setup..."), get_icon("document-properties", 16))
        self.append(item)
        item.connect("activate", lambda x: self.Blueman.setup(device))
        item.show()
        item.props.tooltip_text = _("Run the setup assistant for this device")

        def on_rename(_item, device):
            def on_response(dialog, response_id):
                if response_id == Gtk.ResponseType.ACCEPT:
                    device.set('Alias', alias_entry.get_text())
                elif response_id == 1:
                    device.set('Alias', '')
                dialog.destroy()

            builder = Gtk.Builder()
            builder.set_translation_domain("blueman")
            bind_textdomain_codeset("blueman", "UTF-8")
            builder.add_from_file(UI_PATH + "/rename-device.ui")
            dialog = builder.get_object("dialog")
            dialog.set_transient_for(self.Blueman.window)
            dialog.props.icon_name = "blueman"
            alias_entry = builder.get_object("alias_entry")
            alias_entry.set_text(device.Alias)
            dialog.connect("response", on_response)
            dialog.present()

        item = Gtk.MenuItem.new_with_label("Rename device...")
        item.connect('activate', on_rename, device)
        self.append(item)
        item.show()

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Remove..."), get_icon("edit-delete", 16))
        item.connect("activate", lambda x: self.Blueman.remove(device))
        self.append(item)
        item.show()
        item.props.tooltip_text = _("Remove this device from the known devices list")

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Disconnect"), get_icon("network-offline", 16))
        item.props.tooltip_text = _("Forcefully disconnect the device")

        self.append(item)
        item.show()

        def on_disconnect(item):
            def finished(*args):
                self.unset_op(device)
                
            self.set_op(device, _("Disconnecting..."))
            self.Blueman.disconnect(device,
                                    reply_handler=finished,
                                    error_handler=finished)

        if device.Connected:
            item.connect("activate", on_disconnect)

        else:
            item.props.sensitive = False
コード例 #23
0
ファイル: Services.py プロジェクト: latot/blueman
 def renew(x):
     appl.DhcpClient(Network(device.get_object_path()).get_properties()["Interface"])
コード例 #24
0
ファイル: DhcpClient.py プロジェクト: die-uhus/blueman
    def on_load(self, applet):
        self._any_network = Network()
        self._any_network.connect_signal('property-changed',
                                         self._on_network_prop_changed)

        self.quering = []
コード例 #25
0
ファイル: NetUsage.py プロジェクト: KunLiu1210/blueman
class NetUsage(AppletPlugin, GObject.GObject):
    __depends__ = ["Menu"]
    __icon__ = "network-wireless"
    __description__ = _(
        "Allows you to monitor your (mobile broadband) network traffic usage. Useful for limited data access plans. This plugin tracks every device seperately.")
    __author__ = "Walmis"
    __autoload__ = False
    __gsignals__ = {
    str('monitor-added'): (GObject.SignalFlags.NO_HOOKS, None, (GObject.TYPE_PYOBJECT,)),
    str('monitor-removed'): (GObject.SignalFlags.NO_HOOKS, None, (GObject.TYPE_PYOBJECT,)),
    #monitor, tx, rx
    str('stats'): (
    GObject.SignalFlags.NO_HOOKS, None, (GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT,)),
    }

    _any_network = None

    def on_load(self, applet):
        GObject.GObject.__init__(self)
        self.monitors = []
        self.devices = weakref.WeakValueDictionary()

        self.bus = dbus.SystemBus()

        self._any_network = Network()
        self._any_network.connect_signal('property-changed', self._on_network_property_changed)

        item = create_menuitem(_("Network _Usage"), get_icon("network-wireless", 16))
        item.props.tooltip_text = _("Shows network traffic usage")
        item.connect("activate", self.activate_ui)
        self.Applet.Plugins.Menu.Register(self, item, 84, True)

        self.bus.add_signal_receiver(self.on_nm_ppp_stats, "PppStats", "org.freedesktop.NetworkManager.Device.Serial",
                                     path_keyword="path")
        self.nm_paths = {}

    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

    def _on_network_property_changed(self, _network, key, value, path):
        if key == "Interface" and value != "":
            d = BluezDevice(path)
            d = Device(d)
            self.monitor_interface(Monitor, d, value)

    def activate_ui(self, item):
        Dialog(self)

    def on_unload(self):
        self.bus.remove_signal_receiver(self.on_nm_ppp_stats, "PppStats",
                                        "org.freedesktop.NetworkManager.Device.Serial", path_keyword="path")
        del self._any_network
        self.Applet.Plugins.Menu.Unregister(self)

    def monitor_interface(self, montype, *args):
        m = montype(*args)
        self.monitors.append(m)
        m.connect("stats", self.on_stats)
        m.connect("disconnected", self.on_monitor_disconnected)
        self.emit("monitor-added", m)

    def on_ppp_connected(self, device, rfcomm, ppp_port):
        self.monitor_interface(Monitor, device, ppp_port)

    def on_monitor_disconnected(self, monitor):
        self.monitors.remove(monitor)
        self.emit("monitor-removed", monitor)

    def on_stats(self, monitor, tx, rx):
        self.emit("stats", monitor, tx, rx)
コード例 #26
0
 def __init__(self, device, uuid):
     super(NetworkService, self).__init__(device, uuid)
     self._service = Network(device.get_object_path())
コード例 #27
0
ファイル: DhcpClient.py プロジェクト: DavidGriffith/blueman
    def on_load(self, applet):
        self._any_network = Network()
        self._any_network.connect_signal('property-changed', self._on_network_prop_changed)

        self.quering = []
コード例 #28
0
ファイル: Services.py プロジェクト: aunghtet008900/blueman-1
    def on_request_menu_items(self, manager_menu, device):
        items = []
        appl = AppletService()

        self.has_dun = False
        serial_items = []

        def add_menu_item(manager_menu, service):
            if service.connected:
                item = create_menuitem(service.name, get_x_icon(service.icon, 16))
                manager_menu.Signals.Handle("gobject", item, "activate", manager_menu.on_disconnect, service)
                items.append((item, service.priority + 100))
            else:
                item = create_menuitem(service.name, get_icon(service.icon, 16))
                if service.description:
                    item.props.tooltip_text = service.description
                manager_menu.Signals.Handle("gobject", item, "activate", manager_menu.on_connect, service)
                if service.group == 'serial':
                    serial_items.append(item)
                    if isinstance(service, DialupNetwork):
                        self.has_dun = True
                else:
                    items.append((item, service.priority))
            item.show()

        for service in device.get_services():
            if service.group == 'network':
                manager_menu.Signals.Handle("bluez", Network(device.get_object_path()),
                                            manager_menu.service_property_changed, "PropertyChanged")

            if isinstance(service, Input):
                manager_menu.Signals.Handle("bluez", device, manager_menu.service_property_changed, "PropertyChanged")

            try:
                add_menu_item(manager_menu, service)
            except Exception as e:
                dprint("Failed to load service %s" % service.name)
                traceback.print_exc()
                continue

            if service.group == 'serial':
                for dev in rfcomm_list():
                    if dev["dst"] == device.Address and dev["state"] == "connected":
                        devname = _("Serial Port %s") % "rfcomm%d" % dev["id"]

                        item = create_menuitem(devname, get_x_icon("modem", 16))
                        manager_menu.Signals.Handle("gobject", item, "activate", manager_menu.on_disconnect, service, dev["id"])
                        items.append((item, 120))
                        item.show()

            if service.group == 'network' and service.connected:
                if "DhcpClient" in appl.QueryPlugins():
                    def renew(x):
                        appl.DhcpClient(Network(device.get_object_path()).get_properties()["Interface"])

                    item = create_menuitem(_("Renew IP Address"), get_icon("view-refresh", 16))
                    manager_menu.Signals.Handle("gobject", item, "activate", renew)
                    item.show()
                    items.append((item, 201))

        if self.has_dun and ('PPPSupport' in appl.QueryPlugins() or 'NMDUNSupport' in appl.QueryPlugins()):
            def open_settings(i, device):
                from blueman.gui.GsmSettings import GsmSettings

                d = GsmSettings(device.Address)
                d.run()
                d.destroy()

            item = Gtk.SeparatorMenuItem()
            item.show()
            serial_items.append(item)

            item = create_menuitem(_("Dialup Settings"), get_icon("gtk-preferences", 16))
            serial_items.append(item)
            item.show()
            manager_menu.Signals.Handle("gobject", item, "activate", open_settings, device)

        if len(serial_items) > 1:
            sub = Gtk.Menu()
            sub.show()

            item = create_menuitem(_("Serial Ports"), get_icon("modem", 16))
            item.set_submenu(sub)
            item.show()
            items.append((item, 90))

            for item in serial_items:
                sub.append(item)
        else:
            for item in serial_items:
                items.append((item, 80))

        return items
コード例 #29
0
ファイル: Services.py プロジェクト: vivjoind/blueman
 def renew(x):
     appl.DhcpClient('(s)', Network(device.get_object_path())["Interface"])
コード例 #30
0
 def __init__(self, device: Device, uuid: str):
     super().__init__(device, uuid)
     self._service = Network(obj_path=device.get_object_path())
コード例 #31
0
ファイル: DhcpClient.py プロジェクト: die-uhus/blueman
class DhcpClient(AppletPlugin):
    __description__ = _(
        "Provides a basic dhcp client for Bluetooth PAN connections.")
    __icon__ = "network"
    __author__ = "Walmis"

    _any_network = None

    def on_load(self, applet):
        self._any_network = Network()
        self._any_network.connect_signal('property-changed',
                                         self._on_network_prop_changed)

        self.quering = []

    def on_unload(self):
        del self._any_network

    @dbus.service.method('org.blueman.Applet', in_signature="s")
    def DhcpClient(self, interface):
        self.dhcp_acquire(interface)

    def _on_network_prop_changed(self, _network, key, value):
        if key == "Interface":
            if value != "":
                self.dhcp_acquire(value)

    def dhcp_acquire(self, device):
        if device not in self.quering:
            self.quering.append(device)
        else:
            return

        if device != "":

            def reply(ip_address):
                Notification(_("Bluetooth Network"),
                             _("Interface %(0)s bound to IP address %(1)s") % {
                                 "0": device,
                                 "1": ip_address
                             },
                             pixbuf=get_icon("network-workgroup", 48),
                             status_icon=self.Applet.Plugins.StatusIcon)

                self.quering.remove(device)

            def err(msg):
                dprint(msg)
                Notification(_("Bluetooth Network"),
                             _("Failed to obtain an IP address on %s") %
                             (device),
                             pixbuf=get_icon("network-workgroup", 48),
                             status_icon=self.Applet.Plugins.StatusIcon)

                self.quering.remove(device)

            Notification(
                _("Bluetooth Network"),
                _("Trying to obtain an IP address on %s\nPlease wait..." %
                  device),
                pixbuf=get_icon("network-workgroup", 48),
                status_icon=self.Applet.Plugins.StatusIcon)

            m = Mechanism()
            m.DhcpClient(device,
                         reply_handler=reply,
                         error_handler=err,
                         timeout=120)