Open In App

Locking computer when Bluetooth device is not in range using Python

Python provides the accessibility of using Bluetooth UUID address of one’s phone as a physical security token for any system. This can be done with the help of a Python package named PyBluez. Pybluez can be installed in Linux, Windows, and macOS and it is compatible with Python 2.7 and 3.x.

Required Installations:

The modules needed are:



Approach:

PyBluez is a package with Bluetooth resources which allows Python developers to easily create Bluetooth applications. At first, the necessary packages have been imported into the program. PyBluez is imported as Bluetooth, the schedule is imported for scheduling the program, time package is imported to handle time-related tasks and ctypes is imported to use the existing libraries in other languages, by writing simple wrappers in Python. Following are the steps.

Below is the implementation:






# Import required packages
import schedule
import time
import bluetooth
import ctypes
   
  
def job():
    # Find your bluetooth uuid in your
    # mobile and give set it in the 
    # variable
    inputBdaddr = "XX:XX:XX:XX:XX:XX"
       
    # Variable to find whether the
    # given bluetooth uuid is 
    # present in the discovered devices
    passed = False
       
    # Try to search for the nearby 
    # visible devices
    try:
        # Get the list of discovered devices
        scan = bluetooth.discover_devices()
           
        # Search for your bluetooth uuid 
        # in the scanned devices If found
        # set the variable to true else 
        # set the variable to false
        if inputBdaddr in scan:
            passed = True
              
        else:
            passed = False
              
    except:
        passed = False
           
    # When bluetooth device 
    # is not found, lock the
    # workstation
    if not passed:
        ctypes.windll.user32.LockWorkStation()
           
# Schedule the process 
# to run every 30 seconds
schedule.every(30).seconds.do(job)
   
# Check whether a scheduled 
# task is pending to run or not
while 1:
    schedule.run_pending()
    time.sleep(1)

Limitations:

Since PyBluez is not under active development, Bluetooth detection is probabilistic. discover_devices() will sometimes fail to detect devices that are in range. In this case, it may be a good idea to try again once or twice before giving up.


Article Tags :