-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·99 lines (86 loc) · 2.63 KB
/
server.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
import serial
import anydbm
import re
import os
import time
import sqlite3
def connectToArduino():
print 'Waiting for arduino to connect'
while 1:
# Find device
dev = os.listdir('/dev/')
pattern = re.compile('ttyACM.*')
acm = [];
for d in dev:
if pattern.match(d):
acm.append(d)
# Try to connect
ser = None
for d in acm:
try:
ser = serial.Serial('/dev/'+d, 9600,timeout=0.1)
break
except serial.serialutil.SerialException:
pass
# Check if connected
if ser is not None:
break
# Wait for ready signal
pattern = re.compile('READY')
print 'Waiting for arduino to be ready'
while 1:
try:
res = ser.readline()
if pattern.match(res):
print 'Arduino is ready'
break
except serial.serialutil.SerialException:
ser = connectToArduino()
return ser
def getMobileOpen(dbMobile):
while 1:
try:
cursor = dbMobile.execute('select value from commands where command = "mobileOpen"')
res = cursor.fetchone()
cursor.close()
return res[0]
except sqlite3.OperationalError:
pass
ser = connectToArduino()
dbMobile = sqlite3.connect('/var/www/users', check_same_thread = False)
lastMobileOpen = getMobileOpen(dbMobile)
# Open user acount
db = anydbm.open('brukere', 'c')
adminMode = False;
getIdPattern = re.compile(u'ID: ([0-9A-F]*)')
getUnlockingPattern = re.compile(u'Opening door')
getLockingPattern = re.compile(u'Locking door')
doorIsLocked = False
while 1:
try:
incomming = ser.readline()
if (incomming != ""):
print 'A:'+incomming
res = getIdPattern.findall(incomming)
if (res !=[]):
id = str(res[0])
if (db.has_key(id)):
print 'Toggling door lock for: '+db[id]
ser.write('1')
else:
print 'User is not known, id: '+id
ser.write('0')
elif (getUnlockingPattern.match(incomming)):
doorIsLocked = False;
elif (getLockingPattern.match(incomming)):
doorIsLocked = True;
except serial.serialutil.SerialException:
ser = connectToArduino()
except Exception, e:
print str(e)
ser = connectToArduino()
if (lastMobileOpen < getMobileOpen(dbMobile)):
print 'Toggling door lock for: mobile'
ser.write('1')
lastMobileOpen = getMobileOpen(dbMobile)
time.sleep(.1)