-
Notifications
You must be signed in to change notification settings - Fork 0
/
tilt_listener.py
77 lines (67 loc) · 2.27 KB
/
tilt_listener.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
import sys
import datetime
import time
import MySQLdb
import bluetooth._bluetooth as bluez
import blescan
DB_CONFIG = {
"host": "localhost",
"db": "tiltdb",
"user": "pi",
"passwd": ""
}
TILTS = {
'a495bb10c5b14b44b5121370f02d74de': 'Red',
'a495bb20c5b14b44b5121370f02d74de': 'Green',
'a495bb30c5b14b44b5121370f02d74de': 'Black',
'a495bb40c5b14b44b5121370f02d74de': 'Purple',
'a495bb50c5b14b44b5121370f02d74de': 'Orange',
'a495bb60c5b14b44b5121370f02d74de': 'Blue',
'a495bb70c5b14b44b5121370f02d74de': 'Yellow',
'a495bb80c5b14b44b5121370f02d74de': 'Pink',
}
def distinct(objects):
seen = set()
unique = []
for obj in objects:
if obj['uuid'] not in seen:
unique.append(obj)
seen.add(obj['uuid'])
return unique
def to_celsius(fahrenheit):
return round((fahrenheit - 32.0) / 1.8, 2)
def monitor_tilt():
while True:
beacons = distinct(blescan.parse_events(sock, 10))
print "tried"
db = MySQLdb.connect(**DB_CONFIG)
for beacon in beacons:
if beacon['uuid'] in TILTS.keys():
beer = "beer"
color = TILTS[beacon['uuid']]
unit="fahrenheit"
#timestamp = datetime.datetime.now()
gravity = beacon['minor']
temp = beacon['major'] if unit == "fahrenheit" else to_celsius(beacon['major'])
cur = db.cursor()
insert = ("INSERT INTO stats "
"(beer, color, unit, timestamp, gravity, temp) "
"VALUES (\"{beer}\", \"{color}\", \"{unit}\", now(), {gravity}, {temp})"\
.format(beer=beer, color=color, unit=unit,
gravity=gravity, temp=temp))
print insert
cur.execute(insert)
db.commit()
db.close()
time.sleep(10)
if __name__ == '__main__':
dev_id = 0
try:
sock = bluez.hci_open_dev(dev_id)
print 'Starting pytilt logger'
except:
print 'error accessing bluetooth device...'
sys.exit(1)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
monitor_tilt()