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.
The modules needed are:
- Pybluez: This module allows to use system Bluetooth resources. To install it type the below command in the terminal.
python3 -m pip install pybluez
- Schedule: Schedule Library is used to schedule a task at a particular time every day or a particular day of a week. To install it type the below command in the terminal.
python3 -m pip install schedule
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.
- A function
job()is defined in which bluetooth address of your mobile is declared in the variable
inputBdaddr. The variable
passedis initialized to False to keep track whether the given bluetooth address is found in the discovered devices. To search for the available bluetooth devices nearby,
bluetooth.discover_devices()is used. The results are saved in the variable
scaninside the try-except block. If the required device is found in
scan, the variable
passedis set to true, else false.
passedis found as false, meaning that the required device is not found, the workstation is locked.
- Now schedule the above steps by calling function
job()every 30 seconds. A while loop is used to check whether any scheduled task is pending to run or not.
Below is the implementation:
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course