From 2761239be109ecbde14bcdec11b82d6d2ecf03cb Mon Sep 17 00:00:00 2001 From: dabruh <11458706-dabruh@users.noreply.gitlab.com> Date: Tue, 27 Feb 2024 11:50:10 +0100 Subject: [PATCH] Add script for BT connect/disconnect by name --- .local/bin/btctl | 70 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100755 .local/bin/btctl diff --git a/.local/bin/btctl b/.local/bin/btctl new file mode 100755 index 0000000..6c65422 --- /dev/null +++ b/.local/bin/btctl @@ -0,0 +1,70 @@ +#!/bin/bash + +# btctl - Script to connect or disconnect Bluetooth devices by partial name + +function erro() { + echo "$1" 1>&2 +} + +# Function to get device address by partial name +function get_device_addr() { + local partial_name=$1 + local devices_found + local device_count + + if [ -z "$partial_name" ]; then + echo "Device name not provided." >&2 + return 1 + fi + + # Search for devices containing the partial name, ignoring case + devices_found=$(bluetoothctl devices | grep -i "$partial_name") + + # Count how many devices were found + device_count=$(wc -l <<<"$devices_found") + + if [ "$device_count" -eq 0 ]; then + erro "Device containing '$partial_name' not found." >&2 + return 1 + elif [ "$device_count" -gt 1 ]; then + erro "Multiple devices containing '$partial_name' found. Please specify further." + erro "$devices_found" + return 1 + fi + + # Extract and echo the device address of the single matching device + awk '{print $2}' <<<"$devices_found" +} + +function usage() { + echo "Usage: $(basename "$0") {connect|disconnect|list} " +} + +function perform_action() { + local action=$1 + local partial_name=$2 + local device_addr + + # Check if getting device address was successful + if ! device_addr=$(get_device_addr "$partial_name"); then + return 1 + fi + + if ! bluetoothctl "$action" "$device_addr"; then + echo "$action to device with address $device_addr failed." >&2 + return 1 + fi +} + +case "$1" in +list) + bluetoothctl devices + ;; +connect | disconnect) + perform_action "$1" "$2" + ;; +*) + usage + exit 1 + ;; +esac