-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpicpro.py
executable file
·1412 lines (1155 loc) · 49.9 KB
/
picpro.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""The picpro module provides a simple program-level and command-line-level interface to the PIC programmers made by kitsrus.com.
This module is released under the GPL by its author.
This work would not have been possible without the programming protocol documentation kindly provided by kitsrus as well as the assistance of people at kitsrus.com and in the community.
Send comments or bug reports related to this module to [email protected]
"""
# There should never be a problem with the standard imports. But...
try:
import getopt
import os.path
import re
import struct
import sys
import time
except ImportError:
print "Failed to import standard Python libraries. Please make sure your Python installation is complete and up-to-date."
sys.exit(1)
try:
import serial
except ImportError:
print "Unable to find Python Serial library. Please download and install the serial library from http://www.sf.net/projects/pyserial"
sys.exit(1)
#Is this kosher? I have no idea...
module_location = os.path.dirname(__file__)
if (module_location == ''):
module_location = os.curdir + os.sep
else:
# The following line doesn't appear to be necessary...
# sys.path = [module_location] + sys.path
module_location = module_location + os.sep
import data_string
import hex_file_reader
def print_usage_and_abort():
print handle_command_line.__doc__
sys.exit(1)
def handle_command_line(cmd_args):
"""micropro: program a PIC using the Kits R Us serial/USB PIC programmer.
Arguments:
"-p x" (or "--port=x"): use serial port x
"--pic_type=x": specify type of PIC to be programmed (use '16F84A',
not 'PIC16F84A')
"-i file.hex" (or "--input=file.hex"): specify name of HEX file to use
"--fuse=fuse_name:value": (optional) specify a value for a programming flag
"--ID=PIC_id": (optional) specify ID to be programmed to PIC.
"--program": (default) Program the PIC
"--verify": Verify only, do not program
"-h" (or "--help"): display this message"""
try:
(opts, args) = getopt.getopt(cmd_args[1:], 'p:i:h',
['port=', 'pic_type=', 'input=',
'fuse=', 'ID=', 'help',
'icsp', 'program', 'verify'])
except getopt.GetoptError:
print_usage_and_abort()
if (len(args) != 0):
print_usage_and_abort()
fuses = {}
ID = None
program_flag = False
verify_flag = False
icsp_mode = False
for (opt, value) in opts:
try:
if ((opt == '-h') or (opt == '--help')):
print_usage_and_abort()
elif ((opt == '-p') or (opt == '--port')):
port = value
elif ((opt == '-i') or (opt == '--input')):
hex_file_name = value
elif (opt == '--pic_type'):
pic_type = value
elif (opt == '--fuse'):
split = value.split(':')
fuses[split[0]] = split[1]
elif (opt == '--ID'):
ID = value
elif (opt == '--verify'):
verify_flag = True
elif (opt == '--program'):
program_flag = True
elif (opt == '--icsp'):
icsp_mode = True
else:
print 'Error: Unrecognized option "' + opt + '".'
sys.exit(1)
except SystemExit:
raise
except:
print 'Error: Invalid usage of option "' + opt + '".'
print_usage_and_abort()
program = (program_flag or not verify_flag)
# So let's do this thing...
try:
program_pic_args = dict(port = port,
pic_type = pic_type,
hex_file_name = hex_file_name,
fuses = fuses,
ID = ID,
icsp_mode = icsp_mode)
except NameError:
print "Error: Missing required arguments"
print_usage_and_abort()
program_pic(port, pic_type, hex_file_name, program, fuses = fuses,
ID = ID, icsp_mode = icsp_mode)
class hex_int(int):
'Behaves just like an integer, except its __repr__ in python yields a hex string.'
#self._method_wrap('__xor__')
#self._method_wrap('__rshift__')
def __init__(self, value, radix = 16):
int.__init__(self, value, radix)
def __repr__(self):
if (self >= 0):
return hex(self)
else:
# Avoid "future" warning and ensure eval(repr(self)) == self
return '-' + hex(-self)
def maybe_hex_int(value):
if (isinstance(value, int)):
return hex_int(value)
else:
return value
maybe_hex_int = staticmethod(maybe_hex_int)
_method_wrap = lambda super_method_name: lambda *args, **argd: hex_int.maybe_hex_int(int.__dict__[super_method_name](*args, **argd))
__abs__ = _method_wrap('__abs__')
__add__ = _method_wrap('__add__')
__and__ = _method_wrap('__and__')
__floordiv__ = _method_wrap('__floordiv__')
__invert__ = _method_wrap('__invert__')
__lshift__ = _method_wrap('__lshift__')
__mod__ = _method_wrap('__mod__')
__mul__ = _method_wrap('__mul__')
__neg__ = _method_wrap('__neg__')
__or__ = _method_wrap('__or__')
__pos__ = _method_wrap('__pos__')
__pow__ = _method_wrap('__pow__')
__sub__ = _method_wrap('__sub__')
__xor__ = _method_wrap('__xor__')
__radd__ = _method_wrap('__add__')
__rand__ = _method_wrap('__and__')
__rfloordiv__ = _method_wrap('__floordiv__')
__rmul__ = _method_wrap('__mul__')
__ror__ = _method_wrap('__or__')
__rsub__ = _method_wrap('__rsub__')
__rxor__ = _method_wrap('__xor__')
#---------------------------------------------------
class Chipinfo_Entry(object):
"A single entry from a chipinfo file, with methods for feeding data to protocol_interface."
class Fuse_Error(Exception):
"Indicates an erroneous fuse value."
power_sequence_dict = {'vcc' : 0,
'vccvpp1' : 1,
'vccvpp2' : 2,
'vpp1vcc' : 3,
'vpp2vcc' : 4,
'vccfastvpp1' : 1,
'vccfastvpp2' : 2}
vcc_vpp_delay_dict = {'vcc' : False,
'vccvpp1' : False,
'vccvpp2' : False,
'vpp1vcc' : False,
'vpp2vcc' : False,
'vccfastvpp1' : True,
'vccfastvpp2' : True}
socket_image_dict = {'8pin' : 'socket pin 13',
'14pin' : 'socket pin 13',
'18pin' : 'socket pin 2',
'28Npin' : 'socket pin 1',
'40pin' : 'socket pin 1'}
def __init__(self,
CHIPname, INCLUDE, SocketImage, EraseMode,
FlashChip, PowerSequence, ProgramDelay, ProgramTries,
OverProgram, CoreType, ROMsize, EEPROMsize,
FUSEblank, CPwarn, CALword, BandGap, ICSPonly,
ChipID, fuses):
self.vars = {
'CHIPname' : CHIPname,
'INCLUDE' : INCLUDE,
'SocketImage' : SocketImage,
'erase_mode' : EraseMode,
'FlashChip' : FlashChip,
'power_sequence' : self.power_sequence_dict[PowerSequence.lower()],
'power_sequence_str' : PowerSequence,
'program_delay' : ProgramDelay,
'program_tries' : ProgramTries,
'over_program' : OverProgram,
'core_type' : CoreType,
'rom_size' : ROMsize,
'eeprom_size' : EEPROMsize,
'FUSEblank' : FUSEblank,
'CPwarn' : CPwarn,
'flag_calibration_value_in_ROM' : CALword,
'flag_band_gap_fuse' : BandGap,
'ICSPonly' : ICSPonly,
'ChipID' : ChipID,
'fuses' : fuses}
def get_programming_vars(self):
"Returns a dictionary which can be fed as arguments to Protocol_Interface.init_programming_vars()"
result = dict(
rom_size = self.vars['rom_size'],
eeprom_size = self.vars['eeprom_size'],
core_type = self.vars['core_type'],
flag_calibration_value_in_ROM = self.vars['flag_calibration_value_in_ROM'],
flag_band_gap_fuse = self.vars['flag_band_gap_fuse'],
# T.Nixon says this is the rule for this flag.
flag_18f_single_panel_access_mode = (self.vars['core_type'] == Chipinfo_Reader.core_type_dict['bit16_a']),
flag_vcc_vpp_delay = self.vcc_vpp_delay_dict[self.vars['power_sequence_str'].lower()],
program_delay = self.vars['program_delay'],
power_sequence = self.vars['power_sequence'],
erase_mode = self.vars['erase_mode'],
program_retries = self.vars['program_tries'],
over_program = self.vars['over_program'])
return result
def get_core_bits(self):
core_type = self.vars['core_type']
if (core_type in [1, 2]):
return 16
elif (core_type in [3, 5, 6, 7, 8, 9, 10]):
return 14
elif (core_type in [4]):
return 12
else:
return None
def decode_fuse_data(self, fuse_values):
('Given a list of fuse values, return a dict of symbolic ' +
'(fuse : value) mapping representing the fuses that are set.')
fuse_param_list = self.vars['fuses']
result = {}
for fuse_param in fuse_param_list:
fuse_settings = fuse_param_list[fuse_param]
# Try to determine which of the settings for this fuse is
# active.
# Fuse setting is active if ((fuse_value & setting) ==
# (fuse_value))
# We need to check all fuse values to find the best one.
# The best is the one which clears the most bits and still
# matches. So we start with a best_value of 0xffff (no
# bits cleared.)
best_value = [0xffff] * len(fuse_values)
fuse_identified = False
for setting in fuse_settings:
setting_value = fuse_settings[setting]
if (indexwise_and(fuse_values, setting_value) ==
fuse_values):
# If this setting value clears more bits than
# best_value, it's our new best value.
if (indexwise_and(best_value, setting_value) !=
best_value):
best_value = indexwise_and(best_value,
setting_value)
result[fuse_param] = setting
fuse_identified = True
if (not fuse_identified):
raise self.Fuse_Error, 'Could not identify fuse setting.'
return result
def encode_fuse_data(self, fuse_dict):
result = list(self.vars['FUSEblank'])
fuse_param_list = self.vars['fuses']
for fuse in fuse_dict:
fuse_value = fuse_dict[fuse]
if (fuse not in fuse_param_list):
raise self.Fuse_Error, 'Unknown fuse \"' + fuse + '\".'
fuse_settings = fuse_param_list[fuse]
if (fuse_value not in fuse_settings):
raise self.Fuse_Error, ('Invalid fuse setting: "' +
fuse + '" = "' + fuse_value +
'".')
result = indexwise_and(result, fuse_settings[fuse_value])
return result
def has_eeprom(self):
return (self.vars['eeprom_size'] != 0)
def pin1_location_text(self):
return (self.socket_image_dict[self.vars['SocketImage']])
def fuse_doc(self):
result = ''
fuse_param_list = self.vars['fuses']
for fuse in fuse_param_list:
fuse_settings = fuse_param_list[fuse]
result = result + '\'' + fuse + '\' : ('
first = True
for setting in fuse_settings:
if (not first):
result = result + ', '
result = result + '\'' + setting + '\''
first = False
result = result + ')\n'
return result
#-------------------------------------------------
class Chipinfo_Reader(object):
# Class for reading chipinfo files, which provide information about different types of PICs.
boolean_dict = {'y' : True,
'1' : True,
'n' : False,
'0' : False}
core_type_dict = {'bit16_a' : 1,
'bit16_b' : 2,
'bit14_g' : 3,
'bit12_a' : 4,
'bit14_a' : 5,
'bit14_b' : 6,
'bit14_c' : 7,
'bit14_d' : 8,
'bit14_e' : 9,
'bit14_f' : 10,
'bit12_b' : 11,
'bit14_h' : 12,
'bit16_c' : 13}
class Format_Error(Exception):
"Indicates an error in the chipinfo file's format."
def __init__(self, file_name = '', file = None):
if (file == None):
file = open(file_name, 'U')
def handle_hex(xstr):
return hex_int(xstr, 16)
def handle_int(xstr):
return int(xstr, 10)
def handle_bool(xstr):
return self.boolean_dict[xstr]
def handle_core_type(xstr):
return self.core_type_dict[xstr]
special_handlers = {
'BandGap' : handle_bool,
'CALword' : handle_bool,
'ChipID' : handle_hex,
'CoreType' : handle_core_type,
'CPwarn' : handle_bool,
'EEPROMsize' : handle_hex,
'EraseMode' : handle_int,
'FlashChip' : handle_bool,
'FUSEblank' :
(lambda xstr: map(lambda x: hex_int(x, 16),
xstr.split(' '))),
'ICSPonly' : handle_bool,
'OverProgram' : handle_int,
'ProgramDelay' : handle_int,
'ProgramTries' : handle_int,
'ROMsize' : handle_hex,
}
assignment_regexp = re.compile(r'^(\w+)\s*=\s*(.*)\s*$')
fuse_value_regexp_str = r'"([^"]*)"\s*=\s*([0-9a-fA-F]+(?:&[0-9a-fA-F]+)*)'
fuse_value_regexp = re.compile(fuse_value_regexp_str)
fuse_list_regexp = re.compile(
r'^LIST\d+\s+FUSE(?P<fuse>\d)\s+"(?P<name>[^"]*)"\s*(?P<values>.*)$')
nonblank_regexp = re.compile(r'.*\S.*$')
self.chip_entries = {}
CHIPname = ''
entry = None
line_number = 0;
for line in file:
line_number += 1
match = assignment_regexp.match(line)
if (match):
(lhs, rhs) = match.groups()
# if lhs is 'CHIPname', this is the start of a new section.
if (lhs == 'CHIPname'):
CHIPname = rhs.lower()
entry = {}
self.chip_entries[CHIPname] = entry
entry['CHIPname'] = CHIPname
else:
# General case. CHIPname must be valid.
try:
if (lhs in special_handlers):
entry[lhs] = special_handlers[lhs](rhs.lower())
else:
entry[lhs] = rhs
except NameError:
# Some extraneous line in the file... do we care?
raise self.Format_Error, ("Assignment outside " +
"of chip definition @" +
str(line_number) + " : " +
repr(line))
else:
match = fuse_list_regexp.match(line)
if (match):
(fuse, name, values_string) = match.groups()
fuses = entry.setdefault('fuses', {})
fuses.setdefault(name, {})
values = fuse_value_regexp.findall(values_string)
for value_pair in values:
(lhs, rhs) = value_pair
# rhs may have multiple fuse values, in the form
# xxxx&xxxx&xxxx...
# This means that each xxxx applies to the next
# consecutive fuse.
fuse_values = map(lambda xstr: hex_int(xstr, 16),
rhs.split('&'))
fuse_number = int(fuse)
fuses[name][lhs] = zip(range(fuse_number - 1,
(fuse_number +
len(fuse_values) -
1)),
fuse_values)
elif (nonblank_regexp.match(line)):
raise self.Format_Error, ('Unrecognized line ' +
'format. ' + repr(line))
def get_chip(self, name):
return Chipinfo_Entry(**self.chip_entries[name.lower()])
#-------------------------------------------------
def swab_record(record):
"Given a record from a hex file, return a new copy with adjacent data bytes swapped."
result = []
for x in xrange(0, len(record[1]), 2):
result += record[1][x + 1]
result += record[1][x]
return (record[0], ''.join(result))
#-------------------------------------------------
def range_filter_records(records, lower_bound, upper_bound):
"Given a list of HEX file records, return a new list of HEX file records containing only the HEX data within the specified address range."
result = []
for record in records:
# Need to handle five cases:
# 1: record is completely below lower bound - do nothing
# 2: record is partially below lower bound - slice and append
# 3: record is in range - append
# 4: record is partially above upper bound - slice and append
# 5: record is completely above upper bound - do nothing
if ((record[0] >= lower_bound) and
(record[0] < upper_bound)):
# lower bound is in range and therefore needn't change.
# Part or all of this record will appear in output.
if ((record[0] + len(record[1])) < upper_bound):
# case 3
result.append(record)
else:
# case 4
slice_length = upper_bound - record[0]
result.append((record[0], record[1][0:slice_length]))
elif ((record[0] < lower_bound) and
((record[0] + len(record[1])) > lower_bound)):
# case 2
slice_pos = (lower_bound - record[0])
result.append((lower_bound,
record[1][slice_pos:len(record[1])]))
return result
#-------------------------------------------------
def merge_records(records, default_data, base_address = 0):
"Given a list of HEX file records and a data buffer with its own base address (default=0), merge the HEX file records into a new copy of the data buffer."
result_list = []
mark = 0
point = 0
for record in records:
if ((record[0] < base_address) or
((record[0] + len(record[1])) > (base_address +
len(default_data)))):
raise IndexError, 'Record out of range.'
point = (record[0] - base_address)
if (mark != point):
result_list += default_data[mark:point]
mark = point
# Now we can add the record data to result_list.
result_list += record[1]
mark += len(record[1])
# Fill out the rest of the result with data from default_data, if
# necessary.
if (mark < len(default_data)):
result_list += default_data[mark:]
# String-join result_list and return.
return ''.join(result_list)
#-------------------------------------------------
class Protocol_Interface(object):
"A convenient interface to the DIY serial/USB PIC programmer kits"
class Invalid_Response_Error(Exception):
"Indicates that device did not return the expected response."
class Invalid_Command_Sequence_Error(Exception):
"Indicates commands executed in improper order."
class Invalid_Value_Error(Exception):
"Indicates incorrect value given for command argument."
def __init__(self, port):
self.port = port
# We need to set the port timeout to a small value and use
# polling to simulate variable timeouts. Why? Because any
# time you set the timeout in the serial library, DTR goes
# high, which resets any programmer other than the 149!
self.port.timeout = .1
self.vars_set = False
self.fuses_set = False
self.reset()
# _read(count, timeout)
# Read bytes from the port. Stop when the requested number of
# bytes have been received, or the timeout has passed. In order
# to sidestep issues with the serial library this is done by
# polling the serial port's read() method.
def _read(self, count = 1, timeout = 5):
result = ''
init_time = time.time()
end_time = None
if (timeout != None):
end_time = init_time + timeout
while ((count > 0) and
((end_time == None) or
(time.time() < end_time))):
read_result = self.port.read(count)
count = (count - len(read_result))
result = result + read_result
return result
def _core_bits(self):
self._need_vars()
core_type = self.vars['core_type']
if (core_type in [1, 2]):
return 16
elif (core_type in [3, 5, 6, 7, 8, 9, 10]):
return 14
elif (core_type in [4]):
return 12
else:
return None
def _expect(self, expected, timeout = 10):
"Raise an exception if the expected response byte is not sent by the PIC programmer before timeout."
response = self._read(len(expected), timeout = timeout)
#print "expect: " + expected + " -> " + response
if (response != expected):
raise self.Invalid_Response_Error, ('expected "' +
expected +
'", received ' +
repr(response) +
'.')
def _need_vars(self):
if (not self.vars_set):
raise self.Invalid_Command_Sequence_Error, 'Vars not set'
def _need_fuses(self):
if (not self.fuses_set):
raise self.Invalid_Command_Sequence_Error, 'Fuses not set'
def reset(self):
"Resets the PIC Programmer's on-board controller."
self.vars_set = False
self.fuses_set = False
self.firmware_type = None
self.port.setDTR(True)
time.sleep(.1)
self.port.flushInput()
# Detect whether this unit operates with DTR high, or DTR low.
self.port.setDTR(False)
time.sleep(.1)
# Input was just flushed. If the unit operates with DTR low,
# then the unit is now on, and we should be seeing a 2 byte
# response.
response = self._read(2, timeout=.3)
if (response == ''):
# Apparently the unit operates with DTR high, so...
self.port.setDTR(True)
time.sleep(.1)
response = self._read(2, timeout=.3)
if (len(response) >= 1):
result = (response[0] == 'B')
else:
result = False
if (result and (len(response) == 2)):
self.firmware_type, = struct.unpack('B', response[1])
return result
def _command_start(self, cmd = None):
# Send command 1: if we're at the jump table already this will
# get us out. If we're awaiting command start, this will
# still echo 'Q' and await another command start.
self.port.write('\x01')
self._expect('Q')
# Start command, go to jump table.
self.port.write('P')
# Check for acknowledgement
ack = self._read(1)
result = (ack == 'P')
if (not result):
raise self.Invalid_Response_Error, "No acknowledgement for command start."
# Send command number, if specified
if (cmd != None):
self.port.write(chr(cmd))
return result
def _null_command(self):
cmd = 0
self.port.write(chr(cmd))
return None
def _command_end(self):
cmd = 1
self.port.write(chr(cmd))
ack = self._read(1, timeout=10)
result = (ack == 'Q')
if (not result):
if (ack != ''):
raise self.Invalid_Response_Error, ("Unexpected response (" +
ack +
") in command end.")
else:
raise self.Invalid_Response_Error, "No acknowledgement for command end."
return result
def echo(self, msg = 'X'):
"Instructs the PIC programmer to echo back the message \
string. Returns the PIC programmer's response."
cmd = 2
self._command_start()
result = ''
for c in msg:
self.port.write(chr(cmd))
self.port.write(c)
response = self._read(1)
result = result + response
self._command_end()
return result
def init_programming_vars(
self,
rom_size,
eeprom_size,
core_type,
flag_calibration_value_in_ROM,
flag_band_gap_fuse,
flag_18f_single_panel_access_mode,
flag_vcc_vpp_delay,
program_delay,
power_sequence,
erase_mode,
program_retries,
over_program):
('Inform PIC programmer of general parameters of PIC to be ' +
'programmed. Necessary for use of various other commands.')
cmd = 3
self._command_start(cmd)
flags = ((flag_calibration_value_in_ROM and 1) |
(flag_band_gap_fuse and 2) |
(flag_18f_single_panel_access_mode and 4) |
(flag_vcc_vpp_delay and 8))
command_payload = struct.pack('>HHBBBBBBB',
rom_size,
eeprom_size,
core_type,
flags,
program_delay,
power_sequence,
erase_mode,
program_retries,
over_program)
self.port.write(command_payload)
response = self._read(1)
self._command_end()
result = (response == 'I')
if (result):
self.vars = {'rom_size' : rom_size,
'eeprom_size' : eeprom_size,
'core_type' : core_type,
'flag_calibration_value_in_ROM' : flag_calibration_value_in_ROM,
'flag_band_gap_fuse' : flag_band_gap_fuse,
'flag_18f_single_panel_access_mode' : flag_18f_single_panel_access_mode,
'flag_vcc_vpp_delay' : flag_vcc_vpp_delay,
#'flags' : flags,
'program_delay' : program_delay,
'power_sequence' : power_sequence,
'erase_mode' : erase_mode,
'program_retries' : program_retries,
'over_program' : over_program}
self.vars_set = True
else:
del(self.vars)
self.vars_set = False
return result
def _set_programming_voltages_command(self, on):
"Turn the PIC programming voltages on or off. Must be called as part of other commands which read or write PIC data."
cmd_on = 4
cmd_off = 5
self._need_vars()
if (on):
self.port.write(chr(cmd_on))
expect = 'V'
else:
self.port.write(chr(cmd_off))
expect = 'v'
response = self._read(1)
return (response == expect)
def cycle_programming_voltages(self):
cmd = 6
self._need_vars()
self._command_start(cmd)
response = self._read(1)
self._command_end()
return (response == 'V')
def program_rom(self, data):
"Write data to ROM. data should be a binary string of data, high byte first."
cmd = 7
self._need_vars()
word_count = (len(data) // 2)
if (self.vars['rom_size'] < word_count):
raise self.Invalid_Value_Error, "Data too large for PIC ROM"
if (((word_count * 2) % 32) != 0):
raise self.Invalid_Value_Error, "ROM data must be a multiple of 32 bytes in size."
self._command_start()
self._set_programming_voltages_command(True)
self.port.write(chr(cmd))
word_count_message = struct.pack('>H', word_count)
self.port.write(word_count_message)
self._expect('Y', timeout=20)
try:
for i in xrange(0, (word_count * 2), 32):
self.port.write(data[i:(i + 32)])
self._expect('Y', timeout=20)
self._expect('P', timeout=20)
except self.Invalid_Response_Error:
self.port.flushInput() #We don't get current address for now.
return False
self._set_programming_voltages_command(False)
self._command_end()
return True
def program_eeprom(self, data):
"Write data to EEPROM. Data size must be small enough to fit in EEPROM."
cmd = 8
self._need_vars()
byte_count = len(data)
if (self.vars['eeprom_size'] < byte_count):
raise self.Invalid_Value_Error, "Data too large for PIC EEPROM"
if ((byte_count % 2) != 0):
raise self.Invalid_Value_Error, "EEPROM data must be a multiple of 2 bytes in size."
self._command_start()
self._set_programming_voltages_command(True)
self.port.write(chr(cmd))
byte_count_message = struct.pack('>H', byte_count)
self.port.write(byte_count_message)
self._expect('Y', timeout=20)
for i in xrange(0, byte_count, 2):
self.port.write(data[i:(i + 2)])
self._expect('Y', timeout=20)
# We must send an extra two bytes, which will have no effect.
# Why? I'm not sure. See protocol doc, and read it backwards.
# I'm sending zeros because if we did wind up back at the
# command jump table, then the zeros will have no effect.
self.port.write('\x00\x00')
self._expect('P', timeout = 20)
self._set_programming_voltages_command(False)
self._command_end()
return True
def program_id_fuses(self, id, fuses):
"Program PIC ID and fuses. For 16-bit processors, fuse values \
are not committed until program_18fxxxx_fuse() is called."
cmd = 9
self._need_vars()
core_bits = self._core_bits()
if (core_bits == 16):
if (len(id) != 8):
raise self.Invalid_Value_Error, 'Should have 8-byte ID for 16 bit core.'
if (len(fuses) != 7):
raise self.Invalid_Value_Error, 'Should have 7 fuses for 16 bit core.'
command_body = ('00' + id + struct.pack('<HHHHHHH', *fuses))
response_ok = 'Y'
response_bad = 'N' # Protocol doc doesn't give a "bad" response value.
else:
# 16f88 is 14bit yet has two fuses
if (len(fuses) not in [1,2]):
raise self.Invalid_Value_Error, 'Should have one or two fuses for 14 bit core.'
if (len(id) != 4):
raise self.Invalid_Value_Error, 'Should have 4-byte ID for 14 bit core.'
# Command starts with dual '0' for 14 bit
command_body = ('00' + id + 'FFFF' +
struct.pack('<H', fuses[0]) + ('\xff\xff' * 6))
response_ok = 'Y'
response_bad = 'N'
self._command_start()
self._set_programming_voltages_command(True)
self.port.write(chr(cmd))
self.port.write(command_body)
response = self._read(timeout = 20)
self._set_programming_voltages_command(False)
self._command_end()
if (response == response_ok):
self.fuses_set = True
return (response == response_ok)
def read_rom(self):
"Returns contents of PIC ROM as a string of big-endian values."
cmd = 11
self._need_vars()
# vars['rom_size'] is in words. So multiply by two to get bytes.
rom_size = self.vars['rom_size'] * 2
self._command_start()
self._set_programming_voltages_command(True)
self.port.write(chr(cmd))
response = self._read(rom_size)
self._set_programming_voltages_command(False)
self._command_end()
return data_string.data_string(response)
def read_eeprom(self):
"Returns data stored in PIC EEPROM."
cmd = 12
self._need_vars()
eeprom_size = self.vars['eeprom_size']
self._command_start()
self._set_programming_voltages_command(True)
self.port.write(chr(cmd))
response = self._read(eeprom_size)
self._set_programming_voltages_command(False)
self._command_end()
return data_string.data_string(response)
def read_config(self):
"Reads chip ID and programmed ID, fuses, and calibration."
cmd = 13
self._command_start()
self._set_programming_voltages_command(True)
self.port.write(chr(cmd))
ack = self._read(1)
if (ack != 'C'):
raise self.Invalid_Response_Error, "No acknowledgement from read_config()"
response = self._read(26)
self._set_programming_voltages_command(False)
self._command_end()
config = struct.unpack('<HccccccccHHHHHHHH', response)
result = {'chip_id' : config[0],
'id' : ''.join(config[1:9]),
'fuses' : list(config[9:16]),
'calibrate' : config[16]}
return result
def erase_chip(self):
"Erases all data from chip."
cmd = 14
self._need_vars()
self._command_start(cmd)
response = self._read(1)
self._command_end()
return (response == 'Y')
def rom_is_blank(self, high_byte):
"Returns True if PIC ROM is blank."
cmd = 15
self._need_vars()
expected_b_bytes = (self.vars['rom_size'] // 256) - 1
self._command_start(cmd)
self.port.write(high_byte)
while True:
response = self._read(1)
if (response == 'Y'):
self._command_end()
return True