added device option
[pyfrprog.git] / frprog.py
1 #!/usr/bin/env python
2 import sys, time
3 from SerialPort_linux import *
4
5 # baudrate used for initialization
6 INIT_BAUDRATE=9600
7 # baudrate used for communication with the internal bootloader after init
8 BOOTLOADER_BAUDRATE=38400
9 # baudrate used for communication with the pkernel program that does the flashing eventually
10 KERNEL_BAUDRATE=115200
11
12 # contains the last received checksum from a READ, WRITE or CHECKSUM command
13 last_checksum = 0
14
15 class FlashSequence(object):
16         def __init__(self, address, data):
17                 self.address = address
18                 self.data = data
19
20 def sendByte(byte):
21         tty.write(chr(byte))
22
23 def sendWord(word):
24         sendByte(word & 0xFF)
25         sendByte((word >> 8) & 0xFF)
26
27 def sendDWord(dword):
28         sendByte(dword & 0xFF)
29         sendByte((dword >> 8) & 0xFF)
30         sendByte((dword >> 16) & 0xFF)
31         sendByte((dword >> 24) & 0xFF)
32
33 def recvByte():
34         return ord(tty.read())
35
36 def recvChecksum():
37         global last_checksum
38         last_checksum = recvByte()
39         last_checksum |= (recvByte() << 8)
40
41 def bootromREAD(address, size):
42         # send READ command
43         sendByte(0x01)
44         if (recvByte() != 0xF1):
45                 raise Exception
46         sendByte(0x02)
47         if (recvByte() != 0x82):
48                 raise Exception
49         # tell desired address and size
50         sendDWord(address)
51         sendWord(size)
52         # get binary stream of data
53         data = []
54         for i in range(0, size):
55                 data.append(recvByte())
56         # get checksum
57         recvChecksum()
58         return data
59
60 def bootromWRITE(address, size, data):
61         # send WRITE command
62         sendByte(0x01)
63         if (recvByte() != 0xF1):
64                 raise Exception
65         sendByte(0x03)
66         if (recvByte() != 0x83):
67                 raise Exception
68         # tell desired address and size
69         sendDWord(address)
70         sendWord(size)
71         # write binary stream of data
72         for i in range(0, size):
73                 sendByte(data[i])
74         # get checksum
75         recvChecksum()
76
77 # TODO: test this function!
78 def bootromCALL(address):
79         # send CALL command
80         sendByte(0x01)
81         if (recvByte() != 0xF1):
82                 raise Exception
83         sendByte(0x04)
84         if (recvByte() != 0x84):
85                 raise Exception
86         # tell desired address
87         sendDWord(address)
88         # wait for return parameter - not needed here!
89         #return recvByte()
90
91 # TODO: test this function!
92 def bootromCHECKSUM():
93         # call CHECKSUM command
94         sendByte(0x01)
95         if (recvByte() != 0xF1):
96                 raise Exception
97         sendByte(0x05)
98         if (recvByte() != 0x84):
99                 raise Exception
100         # get checksum
101         recvChecksum()
102
103 def bootromBAUDRATE(baudrate):
104         # send BAUDRATE command
105         sendByte(0x01)
106         if (recvByte() != 0xF1):
107                 raise Exception
108         sendByte(0x06)
109         if (recvByte() != 0x86):
110                 raise Exception
111         # send desired baudrate
112         sendDWord(baudrate)
113
114 def pkernCHIPERASE():
115         sendByte(0x15)
116         if (recvByte() != 0x45):
117                 raise Exception
118         # wait till completion...
119         if (recvByte() != 0x23):
120                 raise Exception
121
122 def pkernERASE(address, size):
123         sendByte(0x12)
124         if (recvByte() != 0x11):
125                 raise Exception
126         sendDWord(address)
127         sendWord(size)
128         if (recvByte() != 0x18):
129                 raise Exception
130
131 def pkernWRITE(address, size, data):
132         # send WRITE command
133         sendByte(0x13)
134         if (recvByte() != 0x37):
135                 raise Exception
136         # tell desired address and size
137         sendDWord(address)
138         sendWord(size)
139
140         # write binary stream of data
141         for i in range(0, size):
142                 sendByte(data[i])
143
144         if (recvByte() != 0x28):
145                 raise Exception
146
147 def readMHXFile(filename): # desired mhx filename
148         fp = open(filename, "r")
149         retval = [] # returns a list of FlashSequence objects
150         linecount = 0
151         for line in fp:
152                 linecount += 1
153                 # get rid of newline characters
154                 line = line.strip()
155
156                 # we're only interested in S2 (data sequence with 3 address bytes) records by now
157                 if line[0:2] == "S2":
158                         byte_count = int(line[2:4], 16)
159                         # just to get sure, check if byte count field is valid
160                         if (len(line)-4) != (byte_count*2):
161                                 print sys.argv[0] + ": Warning - inavlid byte count field in " + \
162                                         sys.argv[1] + ":" + str(linecount) + ", skipping line!"
163                                 continue
164
165                         # address and checksum bytes are not needed
166                         byte_count -= 4
167                         address = int(line[4:10], 16)
168                         datastr = line[10:10+byte_count*2]
169
170                         # convert data hex-byte-string to real byte data list
171                         data = []
172                         for i in range(0, len(datastr)/2):
173                                 data.append(int(datastr[2*i:2*i+2], 16))
174
175                         # add flash sequence to our list
176                         retval.append(FlashSequence(address, data))
177         fp.close()
178         return retval
179
180 def main(argv=None):
181         # check command line arguments
182         if argv is None:
183                 argv = sys.argv
184         if len(argv) != 2 and len(argv) != 4:
185                 print "Usage: " + argv[0] + " <target mhx-file> [-d DEVICE]"
186                 return 1
187
188         # standard serial device to communicate with
189         DEVICE="/dev/ttyUSB0"
190         if len(argv) == 4:
191                 DEVICE = argv[3]
192
193         # read in data from mhx-files before starting
194         try:
195                 try:
196                         bootloaderseqs = readMHXFile("pkernel/pkernel.mhx")
197                 except IOError as error1:
198                         bootloaderseqs = readMHXFile("%PREFIX%/share/frprog/pkernel.mhx")
199                 pkernelseqs = readMHXFile(argv[1])
200         except IOError as error:
201                 print argv[0] + ": Error - couldn't open file " + error.filename + "!"
202                 return 1
203
204         print "Initializing serial port..."
205         global tty
206         tty = SerialPort(DEVICE, 100, INIT_BAUDRATE)
207
208         print "Please press RESET on your board..."
209
210         while True:
211                 tty.write('V')
212                 tty.flush()
213                 try:
214                         if tty.read() == 'F':
215                                 break
216                 except SerialPortException:
217                         # timeout happened, who cares ;-)
218                         pass
219
220         starttime = time.time() # save time at this point for evaluating the duration at the end
221
222         print "OK, trying to set baudrate..."
223         # set baudrate
224         bootromBAUDRATE(BOOTLOADER_BAUDRATE)
225         time.sleep(0.1) # just to get sure that the bootloader is really running in new baudrate mode!
226         del tty
227         tty = SerialPort(DEVICE, 100, BOOTLOADER_BAUDRATE)
228
229         print "Transfering pkernel program to IRAM",
230         # let the fun begin!
231         for seq in bootloaderseqs:
232                 if(seq.address <= 0x40000):
233                         addr = seq.address
234                 else:
235                         continue
236                 #print "RAMing", len(seq.data), "bytes at address", hex(addr)
237                 bootromWRITE(addr, len(seq.data), seq.data)
238                 tty.flush()
239                 sys.stdout.write(".")
240                 sys.stdout.flush()
241         print
242
243         # execute our pkernel finally and set pkernel conform baudrate
244         bootromCALL(0x30000)
245         time.sleep(0.1) # just to get sure that the pkernel is really running!
246         del tty
247         tty = SerialPort(DEVICE, None, KERNEL_BAUDRATE)
248
249         print "Performing ChipErase..."
250         pkernCHIPERASE()
251
252         print "Flashing",
253         for seq in pkernelseqs:
254                 # skip seqs only consisting of 0xffs
255                 seqset = list(set(seq.data))
256                 if len(seqset) == 1 and seqset[0] == 0xff:
257                         continue
258                 #print "Flashing", len(seq.data), "bytes at address", hex(seq.address)
259                 pkernWRITE(seq.address, len(seq.data), seq.data)
260                 tty.flush()
261                 sys.stdout.write(".")
262                 sys.stdout.flush()
263         print
264
265         duration = time.time() - starttime
266         print "Procedure complete, took", round(duration, 2), "seconds."
267
268         sendByte(0x97) # exit and restart
269         print "Program was started. Have fun!"
270
271
272 if __name__ == '__main__':
273         sys.exit(main())