This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
forked from sandalian/bluefence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluefence.py
executable file
·208 lines (173 loc) · 6.72 KB
/
bluefence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/python
'''Bluefence module including the connection services'''
import os
import sys
import argparse
import time
import bluetooth
# Parse the args from command line
parser = argparse.ArgumentParser(description='Bluefence utility')
parser.add_argument('-v', '--verbose', help='Display verbose help', action="store_true")
parser.add_argument('--delay', metavar='SECONDS', type=int, default=10,
help='Time between two scans')
parser.add_argument('-c', '--cmd', metavar='COMMAND', type=str,
default='dbus-send --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.Lock',
help='Command to run when triggered')
parser.add_argument('-m', '--missed', metavar='NUMBER', type=int, default=1,
help='Number of missed scans to trigger command')
parser.add_argument('-w', '--wait', action="store_true",
help='Disables the need for your device to be connected initially')
parser.add_argument('-o', '--once', action="store_true",
help='Only fires the command once')
parser.add_argument('-d', '--distance', type=int,
help='Query the distance. Devices needs to be connected')
parser.add_argument('ADDR', help='Identifier needed')
args = parser.parse_args()
class Connection(object):
'''Connection Abstract Class'''
debug = False
btAddr = ''
status = ''
away_counter = 0
missed = 0
def execute(self):
''' Execute the Command on gone'''
if args.once is not None:
if self.status == 'gone' and self.away_counter == 0:
os.system(args.cmd)
elif self.status == 'gone':
os.system(args.cmd)
def measure(self):
''' interface '''
pass
def logs(self):
''' interface '''
pass
def evaluate(self):
''' interface '''
pass
def connect(self):
'''interface'''
pass
class DistanceService(Connection):
'''Service if distance mode is enabled'''
def __init__(self, btAddr, debug):
self.debug = debug
self.distance = 0
self.away_counter = 0
if self.debug:
print('\033[92m[STATUS]\033[0m', 'Using distance mode')
sys.stdout.flush()
self.bluetooth_addr = btAddr
# Taken and modified from blueproximity.py
def measure(self):
'''Using the hcitool which needs the device to be connected'''
rssi = os.popen("hcitool rssi " + self.bluetooth_addr + " 2>/dev/null").readlines()
# Check if there is a result otherwise the device is not connected
if rssi == []:
self.distance = -255
if self.debug:
print('\033[91m[ERROR]\033[0m Device is not connected')
sys.stdout.flush()
# Extract the rssi and use it as an indicator for the distance
else:
self.distance = int(rssi[0].split(':')[1].strip(' '))
def logs(self):
'''Logs the current status'''
if self.debug:
print('\033[92m[STATUS]\033[0m', 'Device is', self.status,
'for', self.away_counter*5, 'seconds with a distance of', self.distance)
sys.stdout.flush()
def evaluate(self):
'''Check if the distance is smaller then given and otherwise trigger away'''
if self.distance < args.distance:
self.status = 'near'
self.away_counter = 0
else:
self.status = 'away'
self.away_counter += 1
if self.away_counter > args.missed:
self.away_counter = 0
self.status = 'gone'
def connect(self):
rssi = os.popen("hcitool rssi " + self.bluetooth_addr + " 2>/dev/null").readlines()
if rssi != []:
return bluetooth.lookup_name(args.ADDR, timeout=args.delay)
if args.wait:
print('\033[93m[STATUS]\033[0m Device is not paired')
time.sleep(args.delay)
return self.connect()
class NameService(Connection):
'''Service if distance is disable just querry for the device'''
def __init__(self, btAddr, debug):
self.debug = debug
self.name = ''
self.away_counter = 0
if self.debug:
print('\033[92m[STATUS]\033[0m', 'Using name mode')
sys.stdout.flush()
self.bluetooth_addr = btAddr
# Taken form bluefence, this does not need your device to be conncted
def measure(self):
'''Using the bluetooth lookup the devices, which does not need the device to be connected'''
self.name = bluetooth.lookup_name(self.bluetooth_addr, timeout=2)
def logs(self):
'''Logs the current status'''
if self.debug:
print('\033[92m[STATUS]\033[0m', 'Device is', self.status,
'for', self.away_counter*5, 'seconds')
sys.stdout.flush()
def evaluate(self):
'''Check if the device is in range and otherwise trigger away'''
if self.name:
self.status = 'near'
self.away_counter = 0
else:
self.status = 'away'
self.away_counter += 1
if self.away_counter > args.missed:
self.away_counter = 0
self.status = 'gone'
def connect(self):
name = bluetooth.lookup_name(args.ADDR, timeout=args.delay)
if name:
return name
if args.wait:
print('\033[93m[STATUS]\033[0m Waiting for device')
time.sleep(args.delay)
return self.connect()
def main():
'''Main Methond'''
# The command to run when the device is out of range
if args.verbose:
print('\033[92m[STATUS]\033[0m Checking for device')
try:
connection = create_connection()
name = connection.connect()
if name:
if args.verbose:
print('\033[93m[STATUS]\033[0m Found', args.ADDR, 'as', name)
sys.stdout.flush()
while True:
connection.measure()
connection.evaluate()
connection.logs()
connection.execute()
time.sleep(args.delay)
else:
print('\033[91m[ERROR]\033[0m Bluetooth device is not active')
sys.stdout.flush()
# this usually happen when your PC's bluetooth is disabled.
except Exception:
print('\033[91m[ERROR]\033[0m Bluetooth is not active')
sys.stdout.flush()
if args.verbose:
print(Exception)
def create_connection():
'''Factory for the distance service'''
if args.distance is not None:
return DistanceService(args.ADDR, args.verbose)
else:
return NameService(args.ADDR, args.verbose)
if __name__ == '__main__':
main()