Search code examples
python-3.xubuntubluetoothrootpybluez

how to check ping for a bluetooth device in python


i have connected a bluetooth controller to control a rover. i am able to ping the controller using sudo l2ping 84:30:95:06:C6:6C on the terminal. basically i want to execute certain code when ping is not available. i.e., when controller is disconnected. i tried this:

import bluetooth

while True:
    if bluetooth.lookup_name('84:30:95:06:C6:6C'):
        print("do nothing")

    else:
        print("do something")

but this has bit of delay, it takes around 2-3 seconds to give me the output when the controller is disconnected. is there any other way of doing this in python ?


Solution

  • so we can use hcitool to know the status of the bluetooth device. here is a small snippet that worked for me. there is no delay to get the output and this works absolutely fine.

    import subprocess as sp
    
    dev_addr = '84:30:95:06:C6:6C'
    stdoutdata = sp.getoutput("hcitool con")
    
    while True:
        if dev_addr in stdoutdata.split():
            print("do nothing")
    
        if dev_addr not in stdoutdata.split():
            print("do something")