blob: 7fc37260cfdd0112ae11508fc70f21a5797dcf04 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#!/usr/bin/env perl
#
# Quick bluetooth device manager. Finds already paired devices and shows a menu
# (fzf) to choose which one to connect to or disconnect from.
################################################################################
use strict;
use warnings;
use feature 'signatures';
use POSIX qw(isatty);
# In: $type : str ('Paired', 'Bonded', 'Trusted', 'Connected')
# Out: %devs : hash{name:str => mac:str}
sub get_bt_devices($type) {
my @devlines = `bluetoothctl devices $type | grep '^Device'`;
chomp foreach @devlines;
my %devs;
foreach my $devline (@devlines) {
# $devline is like: 'Device DE:E4:38:E5:CF:DC MX Master 3S'
my (undef, $mac, $name) = split ' ', $devline, 3;
$devs{$name} = $mac;
}
return \%devs;
}
# Globals
my $PAIRED = get_bt_devices 'Paired';
my $CONNECTED = get_bt_devices 'Connected';
my $MENULINES = join '', map {
my $connected_str = $CONNECTED->{$_} ? ' (connected)' : '';
"$_$connected_str\n"
} (sort keys %$PAIRED);
chomp $MENULINES;
sub get_selection($selector) {
my $selname = `echo '$MENULINES' | $selector` =~ s/ \(connected\)$//r || exit;
chomp $selname;
return {name => $selname, mac => $PAIRED->{$selname}};
}
sub btconnect($selector) {
my $sel = get_selection($selector);
my $out;
if ($CONNECTED->{$sel->{name}}) {
print "Disconnecting from '$sel->{name}' ($sel->{mac})... ";
$out = `bluetoothctl disconnect $sel->{mac}`;
} else {
print "Connecting to '$sel->{name}' ($sel->{mac})... ";
$out = `bluetoothctl connect $sel->{mac}`;
}
print $? ? "ERROR:\n\n$out\n" : "done\n";
}
if (isatty(*STDIN)) {
# Show menu (fzf) and connect using the CLI
my $query = join ' ', @ARGV;
btconnect("fzf -q '$query'");
} else {
# Show menu (wmenu/dmenu) and connect using the GUI
btconnect($ENV{WAYLAND_DISPLAY} ? 'wmenu -i' : 'dmenu -i');
}
|