blob: 4c2ee8594ce6c7aedfd7b4df2352df021b98b9fd [file] [log] [blame]
Sylvain Munaut0d1e63a2009-12-27 09:27:57 +01001#!/usr/bin/env python
2
3#
4# Utility to deal with sim cards and program the 'magic' ones easily
5#
6#
7# Part of the sim link code of inspired by pySimReader-Serial-src-v2
8#
9#
10# Copyright (C) 2009 Sylvain Munaut <tnt@246tNt.com>
11#
12# This program is free software: you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation, either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20# GNU General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program. If not, see <http://www.gnu.org/licenses/>.
24#
25
26import time
27import serial
28import sys
29
30
31# ----------------------------------------------------------------------------
32# Utils
33# -------------------------------------------------------------------------{{{
34
35def h2b(s):
36 return ''.join([chr((int(x,16)<<4)+int(y,16)) for x,y in zip(s[0::2], s[1::2])])
37
38def b2h(s):
39 return ''.join(['%02x'%ord(x) for x in s])
40
41def swap_nibbles(s):
42 return ''.join([x+y for x,y in zip(s[1::2], s[0::2])])
43
44def rpad(s, l, c='f'):
45 return s + c * (l - len(s))
46
47def lpad(s, l, c='f'):
48 return c * (l - len(s)) + s
49
50def scan_all(base, start=0, end=65536):
51 rv = []
52 s.select_file(base)
53 for v in range(start, end):
54 try:
55 data, sw = s.send_apdu('a0a4000002%04x' % v)
56 if sw == '9000':
57 rv.append( (v, data, sw) )
58 s.select_file(base)
59 except KeyboardInterrupt:
60 return rv, v
61 except:
62 s.reset_card()
63 return rv, end-1
64
65# }}}
66
67
68# ----------------------------------------------------------------------------
69# Main serial communication
70# -------------------------------------------------------------------------{{{
71
72import exceptions
73
74class NoCardError(exceptions.Exception):
75 pass
76class ProtocolError(exceptions.Exception):
77 pass
78
79
80class SerialSimLink(object):
81
82 def __init__(self, device='/dev/ttyUSB0', baudrate=9600, rst='-rts', debug=False):
83 self._sl = serial.Serial(
84 port = device,
85 parity = serial.PARITY_EVEN,
86 bytesize = serial.EIGHTBITS,
87 stopbits = serial.STOPBITS_TWO,
88 timeout = 1,
89 xonxoff = 0,
90 rtscts = 0,
91 baudrate = baudrate,
92 )
93 self._rst_pin = rst
94 self._debug = debug
95
96 rv = self.reset_card()
97 if rv == 0:
98 raise NoCardError()
99 elif rv < 0:
100 raise ProtocoldError()
101
102 def __del__(self):
103 self._sl.close()
104
105 def reset_card(self):
106 rst_meth_map = {
107 'rts': self._sl.setRTS,
108 'dtr': self._sl.setDTR,
109 }
110 rst_val_map = { '+':0, '-':1 }
111
112 try:
113 rst_meth = rst_meth_map[self._rst_pin[1:]]
114 rst_val = rst_val_map[self._rst_pin[0]]
115 except:
116 raise ValueError('Invalid reset pin %s' % self._rst_pin);
117
118 rst_meth(rst_val)
119 time.sleep(0.1) # 100 ms
120 self._sl.flushInput()
121 rst_meth(rst_val ^ 1)
122
123 b = self._rx_byte()
124 if not b:
125 return 0
126 if ord(b) != 0x3b:
127 return -1;
128 self._dbg_print("TS: 0x%x Direct convention" % ord(b))
129
130 while ord(b) == 0x3b:
131 b = self._rx_byte()
132
133 if not b:
134 return -1
135 t0 = ord(b)
136 self._dbg_print("T0: 0x%x" % t0)
137
138 for i in range(4):
139 if t0 & (0x10 << i):
140 self._dbg_print("T%si = %x" % (chr(ord('A')+i), ord(self._rx_byte())))
141
142 for i in range(0, t0 & 0xf):
143 self._dbg_print("Historical = %x" % ord(self._rx_byte()))
144
145 while True:
146 x = self._rx_byte()
147 if not x:
148 break
149 self._dbg_print("Extra: %x" % ord(x))
150
151 return 1
152
153 def _dbg_print(self, s):
154 if self._debug:
155 print s
156
157 def _tx_byte(self, b):
158 self._sl.write(b)
159 r = self._sl.read()
160 if r != b: # TX and RX are tied, so we must clear the echo
161 raise RuntimeError("Bad echo value. Expected %02x, got %s)" % (ord(b), '%02x'%ord(r) if r else '(nil)'))
162
163 def _tx_string(self, s):
164 """This is only safe if it's guaranteed the card won't send any data
165 during the time of tx of the string !!!"""
166 self._sl.write(s)
167 r = self._sl.read(len(s))
168 if r != s: # TX and RX are tied, so we must clear the echo
169 raise RuntimeError("Bad echo value (Expected: %s, got %s)" % (b2h(s), b2h(r)))
170
171 def _rx_byte(self):
172 return self._sl.read()
173
174 def send_apdu_raw(self, pdu):
175 """send_apdu_raw(pdu): Sends an APDU with minimal processing
176
177 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
178 return : tuple(data, sw), where
179 data : string (in hex) of returned data (ex. "074F4EFFFF")
180 sw : string (in hex) of status word (ex. "9000")
181 """
182
183 pdu = h2b(pdu)
184 data_len = ord(pdu[4]) # P3
185
186 # Send first CLASS,INS,P1,P2,P3
187 self._tx_string(pdu[0:5])
188
189 # Wait ack which can be
190 # - INS: Command acked -> go ahead
191 # - 0x60: NULL, just wait some more
192 # - SW1: The card can apparently proceed ...
193 while True:
194 b = self._rx_byte()
195 if b == pdu[1]:
196 break
197 elif b != '\x60':
198 # Ok, it 'could' be SW1
199 sw1 = b
200 sw2 = self._rx_byte()
201 nil = self._rx_byte()
202 if (sw2 and not nil):
203 return '', b2h(sw1+sw2)
204
205 raise RuntimeError('Protocol error')
206
207 # Send data (if any)
208 if len(pdu) > 5:
209 self._tx_string(pdu[5:])
210
211 # Receive data (including SW !)
212 # length = [P3 - tx_data (=len(pdu)-len(hdr)) + 2 (SW1/2) ]
213 to_recv = data_len - len(pdu) + 5 + 2
214
215 data = ''
216 while (len(data) < to_recv):
217 b = self._rx_byte()
218 if (to_recv == 2) and (b == '\x60'): # Ignore NIL if we have no RX data (hack ?)
219 continue
220 if not b:
221 break;
222 data += b
223
224 # Split datafield from SW
225 if len(data) < 2:
226 return None, None
227 sw = data[-2:]
228 data = data[0:-2]
229
230 # Return value
231 return b2h(data), b2h(sw)
232
233 def send_apdu(self, pdu):
234 """send_apdu(pdu): Sends an APDU and auto fetch response data
235
236 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
237 return : tuple(data, sw), where
238 data : string (in hex) of returned data (ex. "074F4EFFFF")
239 sw : string (in hex) of status word (ex. "9000")
240 """
241 data, sw = self.send_apdu_raw(pdu)
242
243 if (sw is not None) and (sw[0:2] == '9f'):
244 pdu_gr = pdu[0:2] + 'c00000' + sw[2:4]
245 data, sw = self.send_apdu_raw(pdu_gr)
246
247 return data, sw
248
249 def send_apdu_checksw(self, pdu, sw="9000"):
250 """send_apdu_checksw(pdu,sw): Sends an APDU and check returned SW
251
252 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
253 sw : string of 4 hexadecimal characters (ex. "9000")
254 return : tuple(data, sw), where
255 data : string (in hex) of returned data (ex. "074F4EFFFF")
256 sw : string (in hex) of status word (ex. "9000")
257 """
258 rv = self.send_apdu(pdu)
259 if sw.lower() != rv[1]:
260 raise RuntimeError("SW match failed ! Expected %s and got %s." % (sw.lower(), rv[1]))
261 return rv
262
263 def select_file(self, dir_list):
264 rv = []
265 for i in dir_list:
266 data, sw = self.send_apdu_checksw("a0a4000002" + i)
267 rv.append(data)
268 return rv
269
270 def read_binary(self, ef, length=None, offset=0):
271 if not hasattr(type(ef), '__iter__'):
272 ef = [ef]
273 r = self.select_file(ef)
274 if length is None:
275 length = int(r[-1][4:8], 16) - offset
276 pdu = 'a0b0%04x%02x' % (offset, (min(256, length) & 0xff))
277 return self.send_apdu(pdu)
278
279 def update_binary(self, ef, data, offset=0):
280 if not hasattr(type(ef), '__iter__'):
281 ef = [ef]
282 self.select_file(ef)
283 pdu = 'a0d6%04x%02x' % (offset, len(data)/2) + data
284 return self.send_apdu(pdu)
285
286 def read_record(self, ef, rec_no):
287 if not hasattr(type(ef), '__iter__'):
288 ef = [ef]
289 r = self.select_file(ef)
290 rec_length = int(r[-1][28:30], 16)
291 pdu = 'a0b2%02x04%02x' % (rec_no, rec_length)
292 return self.send_apdu(pdu)
293
294 def update_record(self, ef, rec_no, data, force_len=False):
295 if not hasattr(type(ef), '__iter__'):
296 ef = [ef]
297 r = self.select_file(ef)
298 if not force_len:
299 rec_length = int(r[-1][28:30], 16)
300 if (len(data)/2 != rec_length):
301 raise ValueError('Invalid data length (expected %d, got %d)' % (rec_length, len(data)/2))
302 else:
303 rec_length = len(data)/2
304 pdu = ('a0dc%02x04%02x' % (rec_no, rec_length)) + data
305 return self.send_apdu(pdu)
306
307 def record_size(self, ef):
308 r = self.select_file(ef)
309 return int(r[-1][28:30], 16)
310
311 def record_count(self, ef):
312 r = self.select_file(ef)
313 return int(r[-1][4:8], 16) // int(r[-1][28:30], 16)
314
315 def run_gsm(self, rand):
316 if len(rand) != 32:
317 raise ValueError('Invalid rand')
318 self.select_file(['3f00', '7f20'])
319 return self.send_apdu('a088000010' + rand)
320
321# }}}
322
323
324# ----------------------------------------------------------------------------
325# Cards model
326# -------------------------------------------------------------------------{{{
327
328class Card(object):
329
330 def __init__(self, sl):
331 self._sl = sl
332
333 def _e_iccid(self, iccid):
334 return swap_nibbles(iccid)
335
336 def _e_imsi(self, imsi):
337 """Converts a string imsi into the value of the EF"""
338 l = (len(imsi) + 1) // 2 # Required bytes
339 oe = len(imsi) & 1 # Odd (1) / Even (0)
340 ei = '%02x' % l + swap_nibbles(lpad('%01x%s' % ((oe<<3)|1, imsi), 16))
341 return ei
342
343 def _e_plmn(self, mcc, mnc):
344 """Converts integer MCC/MNC into 6 bytes for EF"""
345 return swap_nibbles(lpad('%d' % mcc, 3) + lpad('%d' % mnc, 3))
346
347
348class _MagicSimBase(Card):
349 """
350 Theses cards uses several record based EFs to store the provider infos,
351 each possible provider uses a specific record number in each EF. The
352 indexes used are ( where N is the number of providers supported ) :
353 - [2 .. N+1] for the operator name
354 - [1 .. N] for the programable EFs
355
356 * 3f00/7f4d/8f0c : Operator Name
357
358 bytes 0-15 : provider name, padded with 0xff
359 byte 16 : length of the provider name
360 byte 17 : 01 for valid records, 00 otherwise
361
362 * 3f00/7f4d/8f0d : Programmable Binary EFs
363
364 * 3f00/7f4d/8f0e : Programmable Record EFs
365
366 """
367
368 @classmethod
369 def autodetect(kls, sl):
370 try:
371 for p, l, t in kls._files.values():
372 if not t:
373 continue
374 if sl.record_size(['3f00', '7f4d', p]) != l:
375 return None
376 except:
377 return None
378
379 return kls(sl)
380
381 def _get_count(self):
382 """
383 Selects the file and returns the total number of entries
384 and entry size
385 """
386 f = self._files['name']
387
388 r = self._sl.select_file(['3f00', '7f4d', f[0]])
389 rec_len = int(r[-1][28:30], 16)
390 tlen = int(r[-1][4:8],16)
391 rec_cnt = (tlen / rec_len) - 1;
392
393 if (rec_cnt < 1) or (rec_len != f[1]):
394 raise RuntimeError('Bad card type')
395
396 return rec_cnt
397
398 def program(self, p):
399 # Go to dir
400 self._sl.select_file(['3f00', '7f4d'])
401
402 # Home PLMN in PLMN_Sel format
403 hplmn = self._e_plmn(p['mcc'], p['mnc'])
404
405 # Operator name ( 3f00/7f4d/8f0c )
406 self._sl.update_record('8f0c', 2,
407 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
408 )
409
410 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
411 self._sl.update_record('8f0d', 1,
412 rpad(
413 # ICCID
414 '3f00' + '2fe2' + '0a' + self._e_iccid(p['iccid']) +
415
416 # IMSI
417 '7f20' + '6f07' + '09' + self._e_imsi(p['imsi']) +
418
419 # Ki
420 '6f1b' + '10' + p['ki'] +
421
422 # PLMN_Sel
423 '6f30' + '18' + rpad(hplmn, 36)
424
425 , self._files['b_ef'][1]*2)
426 )
427
428 # SMSP ( 3f00/7f4d/8f0e )
429 # FIXME
430
431 # Write PLMN_Sel forcefully as well
432 r = self._sl.select_file(['3f00', '7f20', '6f30'])
433 tl = int(r[-1][4:8], 16)
434
435 hplmn = self._e_plmn(p['mcc'], p['mnc'])
436 self._sl.update_binary('6f30', hplmn + 'ff' * (tl-3))
437
438 def erase(self):
439 # Dummy
440 df = {}
441 for k, v in self._files.iteritems():
442 ofs = 1
443 fv = v[1] * 'ff'
444 if k == 'name':
445 ofs = 2
446 fv = fv[0:-4] + '0000'
447 df[v[0]] = (fv, ofs)
448
449 # Write
450 for n in range(0,self._get_count()):
451 for k, (msg, ofs) in df.iteritems():
452 self._sl.update_record(['3f00', '7f4d', k], n + ofs, msg)
453
454
455class SuperSim(_MagicSimBase):
456
457 name = 'supersim'
458
459 _files = {
460 'name' : ('8f0c', 18, True),
461 'b_ef' : ('8f0d', 74, True),
462 'r_ef' : ('8f0e', 50, True),
463 }
464
465
466class MagicSim(_MagicSimBase):
467
468 name = 'magicsim'
469
470 _files = {
471 'name' : ('8f0c', 18, True),
472 'b_ef' : ('8f0d', 130, True),
473 'r_ef' : ('8f0e', 102, False),
474 }
475
476
477class FakeMagicSim(Card):
478 """
479 Theses cards have a record based EF 3f00/000c that contains the provider
480 informations. See the program method for its format. The records go from
481 1 to N.
482 """
483
484 name = 'fakemagicsim'
485
486 @classmethod
487 def autodetect(kls, sl):
488 try:
489 if sl.record_size(['3f00', '000c']) != 0x5a:
490 return None
491 except:
492 return None
493
494 return kls(sl)
495
496 def _get_infos(self):
497 """
498 Selects the file and returns the total number of entries
499 and entry size
500 """
501
502 r = self._sl.select_file(['3f00', '000c'])
503 rec_len = int(r[-1][28:30], 16)
504 tlen = int(r[-1][4:8],16)
505 rec_cnt = (tlen / rec_len) - 1;
506
507 if (rec_cnt < 1) or (rec_len != 0x5a):
508 raise RuntimeError('Bad card type')
509
510 return rec_cnt, rec_len
511
512 def program(self, p):
513 # Home PLMN
514 r = self._sl.select_file(['3f00', '7f20', '6f30'])
515 tl = int(r[-1][4:8], 16)
516
517 hplmn = self._e_plmn(p['mcc'], p['mnc'])
518 self._sl.update_binary('6f30', hplmn + 'ff' * (tl-3))
519
520 # Get total number of entries and entry size
521 rec_cnt, rec_len = self._get_infos()
522
523 # Set first entry
524 entry = (
525 '81' + # 1b Status: Valid & Active
526 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
527 self._e_iccid(p['iccid']) + # 10b ICCID
528 self._e_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
529 p['ki'] + # 16b Ki
530 24*'f' + 'fd' + 24*'f' + # 25b (unknown ...)
531 rpad(p['smsp'], 20) + # 10b SMSP (padded with ff if needed)
532 10*'f' # 5b (unknown ...)
533 )
534 self._sl.update_record('000c', 1, entry)
535
536 def erase(self):
537 # Get total number of entries and entry size
538 rec_cnt, rec_len = self._get_infos()
539
540 # Erase all entries
541 entry = 'ff' * rec_len
542 for i in range(0, rec_cnt):
543 self._sl.update_record('000c', 1+i, entry)
544
545
546 # In order for autodetection ...
547_cards_classes = [ FakeMagicSim, SuperSim, MagicSim ]
548
549# }}}
550
551
552# ----------------------------------------------------------------------------
553# Main
554# -------------------------------------------------------------------------{{{
555
556import hashlib
557from optparse import OptionParser
558import random
559import re
560
561
562def parse_options():
563
564 parser = OptionParser(usage="usage: %prog [options]")
565
566 parser.add_option("-d", "--device", dest="device", metavar="DEV",
567 help="Serial Device for SIM access [default: %default]",
568 default="/dev/ttyUSB0",
569 )
570 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
571 help="Baudrate used for SIM access [default: %default]",
572 default=9600,
573 )
574 parser.add_option("-t", "--type", dest="type",
575 help="Card type (user -t list to view) [default: %default]",
576 default="auto",
577 )
578 parser.add_option("-e", "--erase", dest="erase", action='store_true',
579 help="Erase beforehand [default: %default]",
580 default=False,
581 )
582
583 parser.add_option("-n", "--name", dest="name",
584 help="Operator name [default: %default]",
585 default="Magic",
586 )
587 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
588 help="Country code [default: %default]",
589 default=1,
590 )
591 parser.add_option("-x", "--mcc", dest="mcc", type="int",
592 help="Mobile Country Code [default: %default]",
593 default=901,
594 )
595 parser.add_option("-y", "--mnc", dest="mnc", type="int",
596 help="Mobile Network Code",
597 default=55,
598 )
599 parser.add_option("-m", "--smsp", dest="smsp",
600 help="SMSP [default: '00 + country code + 5555']",
601 )
602
603 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
604 help="Integrated Circuit Card ID",
605 )
606 parser.add_option("-i", "--imsi", dest="imsi",
607 help="International Mobile Subscriber Identity",
608 )
609 parser.add_option("-k", "--ki", dest="ki",
610 help="Ki (default is to randomize)",
611 )
612
613 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
614 help="Secret used for ICCID/IMSI autogen",
615 )
616 parser.add_option("-j", "--num", dest="num", type=int,
617 help="Card # used for ICCID/IMSI autogen",
618 )
619
620 (options, args) = parser.parse_args()
621
622 if options.type == 'list':
623 for kls in _cards_classes:
624 print kls.name
625 sys.exit(0)
626
627 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
628 parser.error("If either IMSI or ICCID isn't specified, num is required")
629
630 if args:
631 parser.error("Extraneous arguments")
632
633 return options
634
635
636def _digits(secret, usage, len, num):
637 s = hashlib.sha1(secret + usage + '%d' % num)
638 d = ''.join(['%02d'%ord(x) for x in s.digest()])
639 return d[0:len]
640
641def _mcc_mnc_digits(mcc, mnc):
642 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
643
644def _cc_digits(cc):
645 return ('%03d' if cc > 100 else '%02d') % cc
646
647def _isnum(s, l=-1):
648 return s.isdigit() and ((l== -1) or (len(s) == l))
649
650
651def gen_parameters(opts):
652 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
653 options given by the user"""
654
655 # MCC/MNC
656 mcc = opts.mcc
657 mnc = opts.mnc
658
659 if not ((0 < mcc < 999) and (0 < mnc < 999)):
660 raise ValueError('mcc & mnc must be between 0 and 999')
661
662 # Digitize country code (2 or 3 digits)
663 cc_digits = _cc_digits(opts.country)
664
665 # Digitize MCC/MNC (5 or 6 digits)
666 plmn_digits = _mcc_mnc_digits(mcc, mnc)
667
668 # ICCID (20 digits)
669 if opts.iccid is not None:
670 iccid = opts.iccid
671 if not _isnum(iccid, 20):
672 raise ValueError('ICCID must be 20 digits !');
673
674 else:
675 if opts.num is None:
676 raise ValueError('Neither ICCID nor card number specified !')
677
678 iccid = (
679 '89' + # Common prefix (telecom)
680 cc_digits + # Country Code on 2/3 digits
681 plmn_digits # MCC/MNC on 5/6 digits
682 )
683
684 ml = 20 - len(iccid)
685
686 if opts.secret is None:
687 # The raw number
688 iccid += ('%%0%dd' % ml) % opts.num
689 else:
690 # Randomized digits
691 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
692
693 # IMSI (15 digits usually)
694 if opts.imsi is not None:
695 imsi = opts.imsi
696 if not _isnum(imsi):
697 raise ValueError('IMSI must be digits only !')
698
699 else:
700 if opts.num is None:
701 raise ValueError('Neither IMSI nor card number specified !')
702
703 ml = 15 - len(plmn_digits)
704
705 if opts.secret is None:
706 # The raw number
707 msin = ('%%0%dd' % ml) % opts.num
708 else:
709 # Randomized digits
710 msin = _digits(opts.secret, 'imsi', ml, opts.num)
711
712 imsi = (
713 plmn_digits + # MCC/MNC on 5/6 digits
714 msin # MSIN
715 )
716
717 # SMSP
718 if opts.smsp is not None:
719 smsp = opts.smsp
720 if not _isnum(smsp):
721 raise ValueError('SMSP must be digits only !')
722
723 else:
724 smsp = '00%d' % opts.country + '5555' # Hack ...
725
726 # Ki (random)
727 if opts.ki is not None:
728 ki = opts.ki
729 if not re.match('^[0-9a-fA-F]{32}$', ki):
730 raise ValueError('Ki needs to be 128 bits, in hex format')
731
732 else:
733 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
734
735 # Return that
736 return {
737 'name' : opts.name,
738 'iccid' : iccid,
739 'mcc' : mcc,
740 'mnc' : mnc,
741 'imsi' : imsi,
742 'smsp' : smsp,
743 'ki' : ki,
744 }
745
746
747def print_parameters(params):
748
749 print """Generated card parameters :
750 > Name : %(name)s
751 > SMSP : %(smsp)s
752 > ICCID : %(iccid)s
753 > MCC/MNC : %(mcc)d/%(mnc)d
754 > IMSI : %(imsi)s
755 > Ki : %(ki)s
756""" % params
757
758
759if __name__ == '__main__':
760
761 # Get/Gen the parameters
762 opts = parse_options()
763 cp = gen_parameters(opts)
764 print_parameters(cp)
765
766 # Connect to the card
767 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
768
769 # Detect type if needed
770 card = None
771 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
772
773 if opts.type == "auto":
774 for kls in _cards_classes:
775 card = kls.autodetect(sl)
776 if card:
777 print "Autodetected card type %s" % card.name
778 break
779
780 if card is None:
781 print "Autodetection failed"
782 sys.exit(-1)
783
784 elif opts.type in ctypes:
785 card = ctypes[opts.type](sl)
786
787 else:
788 print "Unknown card type %s" % opts.type
789 sys.exit(-1)
790
791 # Erase it if asked
792 if opts.erase:
793 print "Formatting ..."
794 card.erase()
795
796 # Program it
797 print "Programming ..."
798 card.program(cp)
799
800 print "Done !"
801