~jocave/checkbox/hybrid-amd-gpu-mods

« back to all changes in this revision

Viewing changes to providers/plainbox-provider-checkbox/bin/bt_connect

  • Committer: Tarmac
  • Author(s): Brendan Donegan
  • Date: 2013-06-03 11:12:58 UTC
  • mfrom: (2154.2.1 bug1185759)
  • Revision ID: tarmac-20130603111258-1b3m5ydvkf1accts
"[r=zkrynicki][bug=1185759][author=brendan-donegan] automatic merge by tarmac"

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python3
2
 
#
3
 
# This file is part of Checkbox.
4
 
#
5
 
# Copyright 2016 Canonical Ltd.
6
 
#
7
 
# Authors:
8
 
#    Po-Hsu Lin <po-hsu.lin@canonical.com>
9
 
#    Yung Shen <yung.shen@canonical.com>
10
 
#
11
 
# Checkbox is free software: you can redistribute it and/or modify
12
 
# it under the terms of the GNU General Public License version 3,
13
 
# as published by the Free Software Foundation.
14
 
#
15
 
# Checkbox is distributed in the hope that it will be useful,
16
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 
# GNU General Public License for more details.
19
 
#
20
 
# You should have received a copy of the GNU General Public License
21
 
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.
22
 
 
23
 
import sys
24
 
import time
25
 
 
26
 
import bt_helper
27
 
 
28
 
from argparse import ArgumentParser
29
 
 
30
 
 
31
 
def unpair_all(devices, manager):
32
 
    """ Unpairing paired devices and scanning again for rerun jobs."""
33
 
    for dev in devices:
34
 
        try:
35
 
            print("INFO: Unpairing", dev)
36
 
            dev.unpair()
37
 
        except bt_helper.BtException as exc:
38
 
            print("Warning: Unpairing failed", exc)
39
 
    else:
40
 
        # print(flush=True) to bypass plainbox output buffer,
41
 
        # see LP: #1569808 for more details.
42
 
        print("Please reset the device to pairing mode in 13 seconds",
43
 
              flush=True)
44
 
        time.sleep(13)
45
 
        print("INFO: Re-scaning for devices in pairing mode", flush=True)
46
 
        manager.scan()
47
 
 
48
 
 
49
 
def main():
50
 
    """Add argument parser here and do most of the job."""
51
 
    parser = ArgumentParser(description=("Bluetooth auto paring and connect. "
52
 
                                         "Please select one option."))
53
 
    group = parser.add_mutually_exclusive_group(required=True)
54
 
    group.add_argument("--mac", type=str,
55
 
                       help="Pair with a given MAC, not using scan result,")
56
 
    group.add_argument("--mouse", action="store_const",
57
 
                       const="input-mouse", dest="target",
58
 
                       help="List and pair with mouse devices")
59
 
    group.add_argument("--keyboard", action="store_const",
60
 
                       const="input-keyboard", dest="target",
61
 
                       help="List and pair with keyboard devices")
62
 
    args = parser.parse_args()
63
 
 
64
 
    manager = bt_helper.BtManager()
65
 
    # Power on bluetooth adapter and scanning devices in advance.
66
 
    manager.ensure_adapters_powered()
67
 
    manager.scan()
68
 
 
69
 
    if args.mac:
70
 
        # TODO check MAC format
71
 
        print("INFO: Trying to pair with {}".format(args.mac))
72
 
        device = list(manager.get_bt_devices(filters={'Address': args.mac}))
73
 
        paired_device = list(manager.get_bt_devices(
74
 
            filters={'Address': args.mac, 'Paired': True}))
75
 
        if not device:
76
 
            print("ERROR: No pairable device found, terminating")
77
 
            return 1
78
 
 
79
 
        unpair_all(paired_device, manager)
80
 
 
81
 
        for dev in device:
82
 
            try:
83
 
                dev.pair()
84
 
            except bt_helper.BtException as exc:
85
 
                print("ERROR: Unable to pair: ", exc)
86
 
                return 1
87
 
            else:
88
 
                print("INFO: Device paired")
89
 
                return 0
90
 
    else:
91
 
        print("INFO: Listing targeting devices")
92
 
        # Listing device based on RSSI
93
 
        paired_targets = list(manager.get_bt_devices(category=bt_helper.BT_ANY,
94
 
                              filters={'Paired': True, 'Icon': args.target}))
95
 
        if not paired_targets:
96
 
            print("INFO: No paired targeting devices found")
97
 
            manager.scan()
98
 
        else:
99
 
            unpair_all(paired_targets, manager)
100
 
 
101
 
        target_devices = sorted(manager.get_bt_devices(
102
 
            category=bt_helper.BT_ANY, filters={
103
 
             'Paired': False, 'Icon': args.target}),
104
 
             key=lambda x: int(x.rssi or -255), reverse=True)
105
 
        if not target_devices:
106
 
            print("ERROR: No target devices found, terminating")
107
 
            return 1
108
 
        print("INFO: Detected devices (sorted by RSSI; highest first).")
109
 
        # let's assing numbers to devices
110
 
        devices = dict(enumerate(target_devices, 1))
111
 
        for num, dev in devices.items():
112
 
            print("{}. {} (RSSI: {})".format(num, dev, dev.rssi))
113
 
        chosen = False
114
 
        while not chosen:
115
 
            print("Which one would you like to connect to? (0 to exit)")
116
 
            num = input()
117
 
            # TODO: enter as default to 1st device
118
 
            if num == '0':
119
 
                return 1
120
 
            chosen = num.isnumeric() and int(num) in devices.keys()
121
 
        print("INFO: {} chosen.".format(devices[int(num)]))
122
 
        print("INFO: Pairing selected device..")
123
 
        try:
124
 
            devices[int(num)].pair()
125
 
        except bt_helper.BtException as exc:
126
 
            print("ERROR: something wrong: ", exc)
127
 
            return 1
128
 
        else:
129
 
            print("Paired successfully.")
130
 
            return 0
131
 
    # capture all other silence failures
132
 
    return 1
133
 
 
134
 
if __name__ == "__main__":
135
 
    sys.exit(main())