Last active
August 29, 2015 14:04
-
-
Save devunt/254efb8e7cf88efc2d60 to your computer and use it in GitHub Desktop.
BLE rssi catcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import atexit | |
import bluetooth._bluetooth as bluez | |
import struct | |
import subprocess | |
from time import time | |
from threading import Timer | |
MAC_ADDR = struct.pack('6B', 0xc7, 0x51, 0x14, 0xd6, 0xc5, 0xc9) | |
SCAN_ENABLE = struct.pack('2B', 0x01, 0x00) | |
SCAN_DISABLE = struct.pack('2B', 0x00, 0x00) | |
SCAN_OPT = struct.pack('7B', 0x01, 0x10, 0x00, 0x10, 0x00, 0x00, 0x00) | |
class NeuroLinker: | |
def __init__(self): | |
self.S = bluez.hci_open_dev(0) | |
self.L = False | |
self.C = 0 | |
self.LT = time() | |
atexit.register(self.bye) | |
self.tick() | |
self.main() | |
def set_screenlock(self, lock): | |
self.L = lock | |
subprocess.call(['sudo', '-u', 'devunt', '/usr/bin/gnome-screensaver-command', '-l' if lock else '--exit']) | |
def main(self): | |
_scanner = self.scanner() | |
while 1: | |
rssi = _scanner.next() | |
print 'rssi: {0} / C: {1}'.format(rssi, self.C) | |
if self.L: | |
if rssi >= -85: self.C += 1 | |
elif self.C > 0: self.C = 0 | |
if self.C >= 5: | |
self.C = 0 | |
self.set_screenlock(False) | |
else: | |
if rssi < -85: self.C += 1 | |
elif self.C > 0: self.C = 0 | |
if self.C >= 5: | |
self.C = 0 | |
self.set_screenlock(True) | |
def tick(self): | |
if (time() - self.LT > 10) and self.C > 0: | |
self.C = 0 | |
self.set_screenlock(True) | |
t = Timer(1, self.tick) | |
t.daemon = True | |
t.start() | |
def scanner(self): | |
bluez.hci_send_cmd(self.S, 0x08, 0x0b, SCAN_OPT) | |
bluez.hci_send_cmd(self.S, 0x08, 0x0c, SCAN_ENABLE) | |
ft = bluez.hci_filter_new() | |
bluez.hci_filter_all_events(ft) | |
bluez.hci_filter_set_ptype(ft, bluez.HCI_EVENT_PKT) | |
self.S.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, ft) | |
while 1: | |
pkt = self.S.recv(512) | |
if pkt == '': | |
break | |
ptype, event, plen, subevent, num, evtype = struct.unpack('6B', pkt[:6]) | |
if (ptype == 0x04 and | |
event == 0x3e and | |
subevent == 0x02 and | |
evtype == 0x00 and | |
pkt[7:13] == MAC_ADDR): | |
rssi = struct.unpack('b', pkt[-1])[0] | |
self.LT = time() | |
yield rssi | |
def bye(self): | |
bluez.hci_send_cmd(self.S, 0x08, 0x0c, SCAN_DISABLE) | |
def main(): | |
NeuroLinker() | |
if __name__ == '__main__': | |
try: | |
main() | |
except KeyboardInterrupt: | |
exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment