Exemple #1
0
def main():

    args = cli_aruments()
    try:
        hci = Adapter(args.adapter)
    except BluezError as e:
        print(str(e), file=sys.stderr)
        sys.exit(1)

    loop = MainLoop.new(None, False)

    if args.scan_duration:
        timeout_add_seconds(args.scan_duration, scan_timeout, loop)

    hci.onPropertiesChanged(adapter_changed, loop)
    hci.onDeviceAdded(device_found, args.properties, init=True, some="Foo")
    # hci.onDeviceRemoved(device_removed, args.properties)
    # hci.scan()

    # for d in hci.devices():
    #     device_found(d, d.properties, args.properties)

    try:
        loop.run()
    except (KeyboardInterrupt, SystemExit):
        pass
    finally:
        try:
            hci.onDeviceAdded(None)
            hci.onPropertiesChanged(None)
            hci.scan(enable=False)
            hci.clear()
        except:
            pass
Exemple #2
0
    def do_notify_single(self, arg):
        "enable notifications on char and print changed values"
        args = _parse_args_simple(arg)
        timeout_seconds = None
        if len(args) > 1:
            try:
                timeout_seconds = int(args[1])
            except Exception as e:
                print(str(e))
                return
        else:
            print("To few arguments (char, [timeout[)")
            return

        g_char = self.find_char_or_desc_obj(args[0])
        if not g_char:
            print(
                "get:",
                str(g_char),
                "Not valid in GATT database or not resolved",
                file=sys.stderr,
            )
            return

        c = g_char
        try:
            flags = c.flags
            if "notify" in flags or "indicate" in flags:
                c.onValueChanged(generic_notify)
                c.notifyOn()
            elif "read" in flags:
                c.onValueChanged(generic_notify)

        except bluez.BluezDoesNotExistError as e:
            print(c.name, str(e), file=sys.stderr)

        loop = MainLoop.new(None, False)

        self.gatt.dev.onPropertiesChanged(dev_connected_changed)
        timeout = None
        if timeout_seconds:
            timeout = CmdTimeout(timeout_seconds, loop)
        try:
            if timeout_seconds:
                print("Notifying for {} seconds".format(timeout_seconds),
                      file=sys.stderr)
            else:
                print("Notifiying, CTRL+C to end", file=sys.stderr)

            loop.run()
        except (KeyboardInterrupt, bluez.BluezError) as e:
            print("aborted:", self.gatt.dev.name, str(e), file=sys.stderr)
            loop.quit()
            if timeout:
                timeout.canceled = True
Exemple #3
0
    def do_notify(self, arg):
        "enable all notifications and print changed values"
        args = _parse_args_simple(arg)
        timeout_seconds = None
        if len(args) > 0:
            try:
                timeout_seconds = int(args[0])
            except Exception as e:
                print(str(e))
                return

        if not self.gatt:
            print("Disconnected", file=sys.stderr)
            return

        for s in self.gatt.services:
            for c in s.chars:
                try:
                    flags = c.flags
                    if "notify" in flags or "indicate" in flags:
                        c.onValueChanged(generic_notify)
                        c.notifyOn()
                    elif "read" in flags:
                        c.onValueChanged(generic_notify)

                except bluez.BluezDoesNotExistError as e:
                    print(c.name, str(e), file=sys.stderr)
                except bluez.BluezError as e:
                    print(str(e), file=sys.stderr)

        loop = MainLoop.new(None, False)

        self.gatt.dev.onPropertiesChanged(dev_connected_changed)
        timeout = None
        if timeout_seconds:
            timeout = CmdTimeout(timeout_seconds, loop)
        try:
            if timeout_seconds:
                print("Notifying for {} seconds".format(timeout_seconds),
                      file=sys.stderr)
            else:
                print("Notifiying, CTRL+C to end", file=sys.stderr)

            loop.run()
        except (KeyboardInterrupt, bluez.BluezError) as e:
            print("aborted:", self.gatt.dev.name, str(e), file=sys.stderr)
            loop.quit()
            if timeout:
                timeout.canceled = True
Exemple #4
0
    def __init__(self, adapter_name, peripheral_addresses, logger,
                 gatt_description):
        self.adapter_name = adapter_name
        self.peripheral_addresses = peripheral_addresses
        self.logger = logger
        self.scan_filters = {'Transport': 'le'}

        self.mainloop = MainLoop.new(None, False)
        # Use same gatt description for all peripherals (matching uuids to names/formats)
        self.gatt_description = gatt_description

        # state information for all peripherals we want to interact with, dictionary with addr as key
        self.peripherals = {}
        for idx, p_addr in enumerate(self.peripheral_addresses):
            # use upper case addresses
            self.peripheral_addresses[idx] = p_addr.upper()
            self.peripherals[p_addr.upper()] = None

        try:
            self.init_adapter()
        except bluez.BluezError as e:
            logger.error(str(e))
            bluez.ObjectManager.get().onAdapterAdded(adapter_added,
                                                     self.adapter_name, self)
Exemple #5
0
def main():
    parser = ArgumentParser(description="bluetooth tester")
    parser.add_argument(
        "-i",
        "--adapter",
        metavar="hciX",
        default=def_adapter,
        help="bluetooh adapter to use (default={})".format(def_adapter),
    )

    parser.add_argument(
        "-a",
        "--device",
        metavar="addr",
        default=None,
        help="device address to connect to",
    )

    parser.add_argument(
        "-p",
        "--pair",
        default=False,
        action="store_true",
        help="Send pairing request to device, if not paired (Needs an agent)",
    )

    parser.add_argument("-k",
                        "--keep",
                        default=False,
                        action="store_true",
                        help="keep connection alive")

    parser.add_argument(
        "-l",
        "--loop",
        default=False,
        action="store_true",
        help="loop requesting info (sleeps 1s)",
    )

    parser.add_argument(
        "-w",
        "--wait",
        metavar="sec",
        default=1,
        type=int,
        help="time to wait before starting to read",
    )

    args = parser.parse_args()

    print("Scanning on: {}".format(args.adapter))

    try:
        adapter = Adapter(args.adapter)
    except BluezDoesNotExistError as e:
        print(str(e))
        sys.exit(2)

    devs = adapter.devices()
    dev = None

    for d in devs:
        da = d.address()
        if da and da.upper() == args.device.upper():
            print("Found {}: {}".format(args.device, d))
            dev = d

    if not dev:
        adapter.scan()

        sleep(3)
        sr = adapter.devices()

        for d in sr:
            da = d.address()
            if da and da.upper() == args.device.upper():
                print("Found {}: {}".format(args.device, d))
                dev = d

        if not dev:
            print("Could not find device nearby: {}".format(args.device))
            adapter.scan(enable=False)
            sys.exit(1)

        adapter.scan(enable=False)

    if dev.connected():
        print("Already connected: {}".format(dev))
    else:
        if args.pair:
            if not dev.paired():
                print("Device is not paired")
                print("Connecting/pairing to: {}".format(str(dev)))
                dev.pair()
                # waait for paring-agent
                wait_secs = 60
                while wait_secs > 0 and not dev.paired():
                    wait_secs -= 1
                    sleep(1)
                if not dev.paired():
                    print("Pairing failed")
                    sys.exit(1)

                if not dev.trusted():
                    dev.trust(True)
                    print("Device is now trusted")

        if not dev.connect():
            print("Connecting failed")
            sys.exit(1)

    gatt = Gatt(dev, [device_information])

    gatt.resolve()
    if not dev.services_resolved:
        print(
            "Waited not long enough for service resolving, did not find uuids")
        sys.exit(1)

    print("Service UUIDs resolved")

    dev_info = gatt.device_information  # pylint: disable=no-member

    for dinfo in dev_info.chars:
        if dinfo.obj:
            print(dinfo.name, ":", dinfo.read(options={"timeout": 4}))

    if args.wait > 0:
        sleep(args.wait)

    if args.loop:
        loop = MainLoop.new(None, False)

        for dinfo_char in dev_info.chars:
            if dinfo_char.obj:
                # add callback for printing if new value is avalable
                dinfo_char.onPropertiesChanged(print_char)

                # add cyclic read every 1 sec
                timeout_add_seconds(1, read_char, dinfo_char)

        try:
            loop.run()
        except (KeyboardInterrupt, SystemExit) as e:
            print("Interupted:", str(e))

    if not args.keep:
        dev.disconnect()