-
Notifications
You must be signed in to change notification settings - Fork 3
/
adapter.py
executable file
·316 lines (231 loc) · 7.75 KB
/
adapter.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env python
import argparse
import binascii
import etao
import spidev
import struct
from tqdm import tqdm
import time
import RPi.GPIO as GPIO
from card import GCMHeader
BLOCK_SZ = 0x2000
SECTOR_SZ = 0x800
TIMING_LEN = 128
READ_SZ = 0x200 # - (5 + TIMING_LEN)
WRITE_SZ = 0x80
# GPIO pins
GPIO_INT = 7
def addr_from_bytes(addr_bytes):
addr_bytes = list(struct.unpack('>BBBB', addr_bytes))
result = addr_bytes[0] << 17
result += addr_bytes[1] << 9
result += (addr_bytes[2] & 3) << 7
result += addr_bytes[3] & 0x7F
return result
def addr_to_bytes(address):
packed = [0, 0, 0, 0]
packed[0] = (address >> 17) & 0xFF
packed[1] = (address >> 9) & 0xFF
packed[2] = (address >> 7) & 0x3
packed[3] = address & 0x7F
return packed
def read_page(spi, address, amount=READ_SZ):
read_cmd = [0x52]
read_cmd.extend(addr_to_bytes(address))
cmd_len = len(read_cmd) # (5)
out_len = TIMING_LEN
in_len = amount
if in_len > (READ_SZ):
raise Exception('max 0x%x bytes per read' % (READ_SZ))
# time buffer + response size buffer
read_cmd.extend([0xFF for x in range(out_len + in_len)])
response = spi.xfer2(read_cmd)
result = ''.join([chr(x) for x in response])
return result[cmd_len + out_len:]
def write_page(spi, address, data):
ready = False
GPIO.output(GPIO_INT, GPIO.LOW)
status = get_status(spi)
if status & 1:
ready = True
while not ready:
# wait 3.5ms
time.sleep(3.5 / 1000.0)
status = get_status(spi)
if status & 1 and not status & 0x80:
ready = True
else:
print 'waiting for card ready...'
clear_status(spi)
GPIO.output(GPIO_INT, GPIO.HIGH)
write_cmd = [0xf2]
write_cmd.extend(addr_to_bytes(address))
if len(data) > WRITE_SZ:
raise Exception('max write size is 0x%02x' % (WRITE_SZ))
write_cmd.extend([ord(d) for d in data])
spi.xfer2(write_cmd)
# wait 3.5ms
time.sleep(3.5 / 1000.0)
return None
def erase_sector(spi, address):
erase_cmd = [0xf1]
# upper two bytes of address indicate sector
up_addr = addr_to_bytes(address)[:2]
erase_cmd.extend(up_addr)
#finished = False
#last_status = None
#while not finished:
# # wait 1.6ms
# time.sleep(1.62 / 1000.0)
#
# status = get_status(spi)
#
# if status & 2:
# print '0x2 set'
# finished = True
# elif (status >> 7) & 1:
# #if status != last_status:
# print 'erasing/busy?... (0x%02x)' % (status)
# finished = False
# elif status & 1:
# print 'card ready? (0x%02x)' % (status)
# finished = True
# #else:
# # finished = True
spi.xfer2(erase_cmd)
# wait 1.9ms
time.sleep(1.9 / 1000.0)
return None
def clear_status(spi):
spi.xfer2([0x89])
time.sleep(3.5 / 1000.0)
def get_status(spi):
cmd = [0x83, 0x00]
cmd_len = len(cmd)
out_len = cmd_len
in_len = 1
cmd.extend([0xFF for x in range(in_len)])
response = spi.xfer2(cmd)
return response[out_len:][0]
def set_interrupt(spi, enable=True):
cmd = [0x81, 0x00, 0x00, 0x00]
if enable:
cmd[1] = 0x01
spi.xfer2(cmd)
time.sleep(3.5 / 1000.0)
def wake_up(spi):
cmd = [0x87]
spi.xfer2(cmd)
time.sleep(3.5 / 1000.0)
def write_buffer(spi):
cmd = [0x82]
spi.xfer2(cmd)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--read', type=str)
parser.add_argument('-w', '--write', type=str, nargs=2,
help='original_file updated_file - writes diffs')
args = parser.parse_args()
spi = spidev.SpiDev()
spi.open(0, 0)
spi.mode = 0b00
spi.max_speed_hz = 1000000 * 12 # 12 MHz (12.5 MHz is average on console)
spi.cshigh = False
# GPIO setup
GPIO.setmode(GPIO.BOARD)
GPIO.setup(GPIO_INT, GPIO.OUT)
GPIO.output(GPIO_INT, GPIO.LOW)
# opening sequence?
opener_response = spi.xfer2([0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00], 800000)
opener_response = ''.join([chr(x) for x in opener_response])
print 'opening sequence:', binascii.hexlify(opener_response)
GPIO.output(GPIO_INT, GPIO.HIGH)
cleared_status = False
while not cleared_status:
print 'clearing status...'
clear_status(spi)
status = get_status(spi)
print 'getting status: 0x%02x' % (status)
print etao.get_bits(status)
if status & 1:
cleared_status = True
print 'setting interrupt...'
set_interrupt(spi)
print 'unlock command?'
read_page(spi, 0x7fec9, amount=29)
print 'getting first page...'
first_page = read_page(spi, 0, amount=38)
print binascii.hexlify(first_page)
header = GCMHeader()
header.load_bytes(first_page)
for k in vars(header):
if k == 'serial':
continue
print k, vars(header)[k]
print 'serial: %s' % (binascii.hexlify(header.serial))
print 'size: %u Mb' % (header.sizeMb)
if header.sizeMb > 128:
print 'ERROR: maximum size is 128 Mb'
GPIO.cleanup()
return
# total size of card in bytes
# (16 blocks per Megabit, 0x2000 bytes per block)
total_size = header.sizeMb * 0x10 * BLOCK_SZ
if args.read is not None:
output = open(args.read, 'wb')
content = ''
num_reads = total_size / READ_SZ
if num_reads * READ_SZ < total_size:
num_reads += 1
# print '%u / %u = %u' % (total_size, READ_SZ, total_size / READ_SZ)
# print 'total reads: %u' % (num_reads)
for i in tqdm(range(num_reads)):
start_addr = i * READ_SZ
if start_addr + READ_SZ > total_size:
read_amount = (total_size - start_addr) % READ_SZ
# print 'final read size %u' % (read_amount)
else:
read_amount = READ_SZ
# print 'read #%u @ 0x%08x' % (i, start_addr)
get_page = read_page(spi, start_addr, amount=read_amount)
# print binascii.hexlify(get_page)
# print 'got %u bytes' % (len(get_page))
content += get_page
# print 'content length %u' % (len(content))
output.write(content)
output.close()
elif args.write is not None:
original = open(args.write[0], 'rb')
inputf = open(args.write[1], 'rb')
original_content = original.read()
new_content = inputf.read()
original.close()
inputf.close()
if len(original_content) != len(new_content) or len(new_content) != total_size:
raise Exception('image size mismatch')
diff_count = 0
for i in tqdm(range(total_size / BLOCK_SZ)):
pos = i * BLOCK_SZ
original_sector = original_content[pos:pos + BLOCK_SZ]
new_sector = new_content[pos:pos + BLOCK_SZ]
#print 'writing block %u of %u' % (i + 1, total_size / BLOCK_SZ)
if original_sector != new_sector:
diff_count += 1
#print 'erase sector @ 0x%04x' % (pos)
erase_sector(spi, pos)
for j in range(BLOCK_SZ / WRITE_SZ):
slice_pos = pos + (j * WRITE_SZ)
#print 'write slice @ 0x%08x' % (slice_pos)
new_slice = new_sector[j * WRITE_SZ:(j + 1) * WRITE_SZ]
write_page(spi, slice_pos, new_slice)
time.sleep(4.0 / 1000.0)
GPIO.output(GPIO_INT, GPIO.LOW)
get_status(spi)
clear_status(spi)
GPIO.output(GPIO_INT, GPIO.HIGH)
time.sleep(14.0 / 1000.0)
print 'updated %u blocks' % (diff_count)
spi.close()
GPIO.cleanup()
if __name__ == '__main__':
main()