Locking computer when Bluetooth device is not in range using Python
Last Updated :
16 Jul, 2020
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.
- A function
job()
is defined in which bluetooth address of your mobile is declared in the variable inputBdaddr
. The variable passed
is 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 scan
inside the try-except block. If the required device is found in scan
, the variable passed
is set to true, else false.
- If
passed
is 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:
import schedule
import time
import bluetooth
import ctypes
def job():
inputBdaddr = "XX:XX:XX:XX:XX:XX"
passed = False
try :
scan = bluetooth.discover_devices()
if inputBdaddr in scan:
passed = True
else :
passed = False
except :
passed = False
if not passed:
ctypes.windll.user32.LockWorkStation()
schedule.every( 30 ).seconds.do(job)
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.
Share your thoughts in the comments
Please Login to comment...