Brunosimioni's Blog

Tecnologia, informação e opinião.

Posts Tagged ‘hcitool

Script de proximidade para bluetooth.

leave a comment »

E aí minha gente. Segue um pequeno script pra lidar com qualidade de sinal bluetooth. É necessário sua adaptação pra funcionar corretamente.

Um abraço e boa sorte!

#!/bin/bash
# Baseado em http://gentoo-wiki.com/Talk:TIP_Bluetooth_Proximity_Monitor

# PARA EDITAR!

# MAC do dispositivo Bluetooth
DEVICE="00:00:00:00:00:00" 

# Distancia em segundos de intervalo de checagem.
CHECK_INTERVAL=2

# Limitante do RSSI
THRESHOLD=-15

# Comando a rodar quando você estiver distante
FAR_CMD='/usr/bin/gnome-screensaver-command --activate'

# Comando a rodar quando estiver próximo
NEAR_CMD='/usr/bin/gnome-screensaver-command --poke'

HCITOOL="/usr/bin/hcitool"
STARTX_PID=0
DEBUG="/tmp/btproximity.log"

connected=0

function msg {
    echo "$1" #>> "$DEBUG"
}

function check_connection {
    connected=0;
    found=0
    for s in `$HCITOOL con`; do
        if [[ "$s" == "$DEVICE" ]]; then
            found=1;
        fi
    done
    if [[ $found == 1 ]]; then
        connected=1;
    else
       msg 'Attempting connection...'
        if [ -z "`$HCITOOL cc $DEVICE 2>&1`" ]; then
            msg 'Connected.'
            connected=1;
        else
                if [ -z "`l2ping -c 2 $DEVICE 2>&1`" ]; then
                        if [ -z "`$HCITOOL cc $DEVICE 2>&1`" ]; then
                            msg 'Connected.'
                            connected=1;
                        else
                        msg "ERROR: Could not connect to device $DEVICE."
                        connected=0;
                        fi
                fi
        fi
    fi
}

check_connection

while [[ $connected -eq 0 ]]; do
    check_connection
    sleep 3
done

name=`$HCITOOL name $DEVICE`
msg "Monitoring proximity of \"$name\" [$DEVICE]";

state="near"
while /bin/true; do

    check_connection

    if [[ $connected -eq 1 ]]; then
        rssi=$($HCITOOL rssi $DEVICE | sed -e 's/RSSI return value: //g')

        if [[ $rssi -le $THRESHOLD ]]; then
            if [[ "$state" == "near" ]]; then
                msg "*** Device \"$name\" [$DEVICE] has left proximity"
                state="far"
                $FAR_CMD > /dev/null 2>&1
            fi
        else
            if [[ "$state" == "far" && $rssi -ge $[$THRESHOLD+2] ]]; then
                msg "*** Device \"$name\" [$DEVICE] is within proximity"
                state="near"
                $NEAR_CMD > /dev/null 2>&1
                STARTX_PID=$(pgrep startx)
            fi
        fi
        msg "state = $state, RSSI = $rssi"
    fi

    sleep $CHECK_INTERVAL
done

Written by Bruno Simioni

11 de julho de 2011 at 8:42 PM

Publicado em Experimentos

Tagged with , , ,