prep for python kernelprog
[pyfrprog.git] / pkernel / kernel.py
1 #!/usr/bin/env python
2 import sys, time
3 from SerialPort_linux import *
4
5 # serial device to communicate with
6 DEVICE="/dev/ttyUSB0"
7 # baudrate used for communication with pkernel
8 KERNEL_BAUDRATE=38400
9
10 def pkernWRITE(address, size, data):
11         # send WRITE command
12         sendByte(0x01)
13         if (recvByte() != 0xF1):
14                 raise Exception
15         sendByte(0x03)
16         if (recvByte() != 0x83):
17                 raise Exception
18         # tell desired address and size
19         sendDWord(address)
20         sendWord(size)
21         # write binary stream of data
22         for i in range(0, size):
23                 sendByte(data[i])
24         # get checksum
25         recvChecksum()
26
27 print "Initializing serial port..."
28 tty = SerialPort(DEVICE, 500, KERNEL_BAUDRATE)
29
30 # check command line arguments
31 if len(sys.argv) != 2:
32         print "Usage: " + sys.argv[0] + " [mhx-file]"
33         sys.exit(1)
34
35 # read in data from mhx-file before starting
36 try:
37         fp = open(sys.argv[1], "r")
38 except IOError:
39         print sys.argv[0] + ": Error - couldn't open file " + sys.argv[1] + "!"
40         sys.exit(1)
41
42 linecount = 0
43 for line in fp:
44         linecount += 1
45         # get rid of newline characters
46         line = line.strip()
47
48         # we're only interested in S2 (data sequence with 3 address bytes) records by now
49         if line[0:2] == "S2":
50                 byte_count = int(line[2:4], 16)
51                 # just to get sure, check if byte count field is valid
52                 if (len(line)-4) != (byte_count*2):
53                         print sys.argv[0] + ": Warning - inavlid byte count field in " + \
54                                 sys.argv[1] + ":" + str(linecount) + ", skipping line!"
55                         continue
56
57                 # address and checksum bytes are not needed
58                 byte_count -= 4
59                 address = int(line[4:10], 16)
60                 datastr = line[10:10+byte_count*2]
61
62                 # convert data hex-byte-string to real byte data list
63                 data = []
64                 for i in range(0, len(datastr)/2):
65                         data.append(int(datastr[2*i:2*i+2], 16))
66
67                 # add flash sequence to our list
68                 flashseqs.append(FlashSequence(address, data))
69
70 print "The following flash sequences have been read in:"
71 for seq in flashseqs:
72         print hex(seq.address) + ":", seq.data
73
74
75 # let the fun begin!
76 for seq in flashseqs:
77         print "Flashing", len(seq.data), "bytes at address", hex(seq.address)
78         pkernWRITE(seq.address, len(seq.data), seq.data)
79
80 print "Reset your board now to run code from Flash"