Script to switch a monitor on and off
[einar-bin] / autolock.py
1 #!/usr/bin/env python
2 # Automatically lock the screen when bluetooth beacon moves out of range
3
4 import time
5 from beacontools import BeaconScanner, IBeaconFilter, IBeaconAdvertisement
6 import signal
7 import dbus
8 from gi.repository import Gio
9
10 global isHere, beaconTimeout
11 global screenSaverSetActive, screenSaverGetActive, sessionIdleTime
12
13 def handler(signum, frame):
14 scanner.stop()
15 exit(0)
16
17 def callback(bt_addr, rssi, packet, additional_info):
18 global isHere
19 isHere = True
20
21 sessionBus = dbus.SessionBus()
22
23 screenSaver = sessionBus.get_object("org.gnome.ScreenSaver", "/org/gnome/ScreenSaver")
24 screenSaverIface = dbus.Interface(screenSaver, 'org.gnome.ScreenSaver')
25 screenSaverSetActive = screenSaverIface.get_dbus_method("SetActive")
26 screenSaverGetActive = screenSaverIface.get_dbus_method("GetActive")
27
28 mutter = sessionBus.get_object('org.gnome.Mutter.IdleMonitor', '/org/gnome/Mutter/IdleMonitor/Core')
29 mutterIface = dbus.Interface(mutter, 'org.gnome.Mutter.IdleMonitor')
30 sessionIdleTime = mutterIface.get_dbus_method("GetIdletime")
31
32 # scan for all iBeacon advertisements regardless from which beacon
33 #scanner = BeaconScanner(callback,
34 # packet_filter=IBeaconAdvertisement
35 #)
36
37 signal.signal(signal.SIGINT, handler)
38
39 beaconTimeout=0
40
41 while True:
42 isHere = False
43 scanner = BeaconScanner(callback,
44 device_filter=IBeaconFilter(uuid="INSERT BEACON UUID HERE")
45 )
46 scanner.start()
47 time.sleep(10)
48 scanner.stop()
49 idleTime = sessionIdleTime() / 1000
50
51 if isHere:
52 #print("Beacon observed")
53 beaconTimeout = 0
54 else:
55 beaconTimeout += 10
56 #print("Beacon not observed,", idleTime, "seconds since last activity,", beaconTimeout, "seconds since beacon seen")
57 if idleTime >= 60 and beaconTimeout >= 60:
58 if not screenSaverGetActive():
59 print("No activity and not seen for at least 60 seconds, locking screen")
60 screenSaverSetActive(True)