This repository has been archived by the owner on Mar 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notdoord.py
executable file
·224 lines (198 loc) · 6.27 KB
/
notdoord.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#! /usr/bin/env python3
# Bodge electronic door locks
import sys
import crc16
import serial
import time
import argparse
import os
def dbg(msg):
print(msg)
def encode64(val):
if val < 26:
return chr(val + ord("A"))
val -= 26;
if val < 26:
return chr(val + ord("a"))
val -= 26;
if val < 10:
return chr(val + ord("0"))
val -= 10;
if val == 0:
return '+';
if val == 1:
return '/';
return '*';
def decode64(c):
if c >= 'A' and c <= 'Z':
return ord(c) - ord('A')
if c >= 'a' and c <= 'z':
return ord(c) + 26 - ord('a')
if c >= '0' and c <= '9':
return ord(c) + 52 - ord('0')
if c == '+':
return 62
if c == '/':
return 63
raise Exception("Bad base64 character: '%s'" % c)
def encoded_time():
t = int(time.time())
s = ""
for i in range(6):
s += encode64(t & 0x3f)
t >>= 6;
return s
def decode_time(s):
t = 0
for i in range(len(s)):
t |= decode64(s[i]) << (i * 6)
return t
def crc_str(s):
return "%04X" % crc16.crc16xmodem(s)
def OpenSerial(name):
return serial.Serial(name, 9600, timeout=30)
class SimpleDoor():
def __init__(self, port_name):
self.port_name = port_name
self.ser = None
self.public_open = False
self.open_expires = None
self.keys = []
self.seen_event = False
self.seen_kp = None
def dbg(self, *args):
dbg(*args)
def load_keys(self, filename):
self.keys = []
with open(filename, "rt") as f:
header = f.readline().split()
if header != ["card_id", "pin", "user_id"]:
raise Exception("Bad card file header")
for l in f:
card, pin, _ = l.split()
self.keys.append("%s %s" % (card.upper(), pin))
def do_cmd(self, cmd):
dbg("Sending %s" % cmd)
self.ser.write(cmd.encode())
self.ser.write(crc_str(cmd).encode())
self.ser.write(b"\n")
r = None
while r is None:
r = self.read_response()
return r
def read_response(self):
r = self.ser.readline().decode()
self.dbg("Response: %s" % r[:-1])
if len(r) == 0:
raise Exception("Timeout waiting for response")
if len(r) < 5:
return None
if r[0] == '#':
return None
crc = r[-5:-1]
r = r[:-5]
if crc != crc_str(r):
raise Exception("CRC mismatch (exp %s got %s)" % (crc, crc_str(r)))
if r[0] == 'E':
self.seen_event = True;
elif r[0] == 'Y':
kp_char = r[2]
if self.seen_kp is None:
self.seen_kp = ''
self.seen_kp += kp_char
else:
return r
return None
def do_cmd_expect(self, cmd, response, error):
r = self.do_cmd(cmd)
if r != response:
self.dbg("Expected %r got %r" % (response, r))
raise Exception(error)
def do_kp(self, kp):
self.dbg("Keypad %s" % kp)
if self.public_open and kp == '#':
self.do_cmd("U0")
def check_open_day(self):
try:
with open("/tmp/open-day", "rt") as f:
hours = int(f.read())
os.unlink("/tmp/open-day")
self.public_open = True
self.open_expires = time.monotonic() + hours * 3600
self.dbg("Opening Space for %d hours" % hours)
except FileNotFoundError:
pass
if self.public_open:
if time.monotonic() >= self.open_expires:
self.public_open = False
self.dbg("Closing Space")
def read_event(self):
while True:
r = self.do_cmd("G0")
if r[:2] != 'V0':
raise Exception("Failed to get log event")
if r == 'V0':
return
print("Log event:" , r[2:])
self.do_cmd_expect("C0", "A0", "Error clearing event log")
def run(self):
self.resync()
next_tick = time.monotonic()
while True:
self.check_open_day()
while self.ser.inWaiting():
self.read_response()
if self.seen_event:
self.seen_event = False
self.read_event()
if self.seen_kp is not None:
k = self.seen_kp
self.seen_kp = None
self.do_kp(k)
if time.monotonic() < next_tick:
time.sleep(0.1)
else:
self.send_ping()
next_tick += 5
def send_ping(self):
t = encoded_time()
self.do_cmd_expect("P0" + t, "P1" + t, "Machine does not go ping")
def key_hash(self):
crc = 0
for key in self.keys:
crc = crc16.crc16xmodem(key, crc)
crc = crc16.crc16xmodem(chr(0), crc)
self.dbg("key hash %04X" % crc)
return "%04X" % crc
def resync(self):
self.dbg("Resync")
if self.ser is None:
self.ser = OpenSerial(self.port_name)
self.ser.write(b"X\n")
time.sleep(1)
# Wait for a 1s quiet period
while self.ser.inWaiting():
while self.ser.inWaiting():
self.ser.read(1)
time.sleep(0.1)
# Enumerate devices
self.do_cmd_expect("S0", "S1", "Device not accepting address")
self.send_ping()
hash_result = "H0" + self.key_hash()
r = self.do_cmd("K0")
if r != hash_result:
self.dbg("Uploading keys")
self.do_cmd_expect("R0", "A0", "Device key reset failed")
for key in self.keys:
self.do_cmd_expect("N0" + key, "A0", "Device not accepting keys")
self.do_cmd_expect("K0", hash_result, "Key upload corrupt")
def main():
parser = argparse.ArgumentParser(description='Simple hackspace door daemon')
parser.add_argument('--device', required=True, help='The serial device for the Arduino e.g. /dev/ttyUSB0')
parser.add_argument('--cardsPath', required=True, help='Path to the cards.dat file')
args = parser.parse_args()
d = SimpleDoor(args.device)
d.load_keys(args.cardsPath)
d.run()
if __name__ == "__main__":
main()