1 #!/usr/bin/env python 2 3 """ 4 A ROM upload utility for the Arduino-Am29F010 interface. 5 6 Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along 18 with this program. If not, see <http://www.gnu.org/licenses/>. 19 """ 20 21 from serial import Serial 22 from time import sleep 23 import sys 24 25 port = "/dev/ttyUSB0" 26 rate = 115200 27 28 def openPort(): 29 global s 30 s = Serial(port, rate) 31 s.setTimeout(5) 32 s.readline() 33 34 def closePort(): 35 global s 36 s.close() 37 s = None 38 39 def writeToPort(data): 40 s.write(data) 41 s.flush() 42 print >>sys.stderr, data.rstrip() 43 44 def readFromPort(): 45 resp = s.readline().rstrip("\r\n") 46 if resp == "?": 47 resp = s.readline().rstrip("\r\n") 48 return resp 49 50 def console(): 51 try: 52 while 1: 53 cmd = raw_input("> ") 54 if cmd: 55 s.write(cmd + "\n") 56 s.flush() 57 print s.readline().rstrip("\r\n") 58 except EOFError: 59 print "Session closed." 60 61 def upload(filename, sector): 62 data = open(filename, "rb").read() 63 64 if len(data) != 0x4000: 65 print >>sys.stderr, "File", filename, "is not", 0x4000, "bytes long." 66 return False 67 68 print >>sys.stderr, "Erasing sector", sector, "..." 69 70 writeToPort("S%x\n" % sector) 71 resp = readFromPort() 72 if resp != "S": 73 print >>sys.stderr, "Sector %d erase failed: %s" % (sector, resp) 74 return False 75 76 print >>sys.stderr, "Uploading", filename, "to sector", sector, "..." 77 78 i = 0 79 while i < 0x4000: 80 value = ord(data[i]) 81 addr = (sector << 14) | i 82 83 writeToPort("P%04x%02x\n" % (addr, value)) 84 resp = readFromPort() 85 if resp != "P": 86 print >>sys.stderr, "Program of location %04x failed: %s" % (addr, resp) 87 return False 88 89 i += 1 90 91 return True 92 93 if __name__ == "__main__": 94 openPort() 95 96 try: 97 if "-i" in sys.argv: 98 console() 99 elif len(sys.argv) > 1: 100 if len(sys.argv) > 3 and sys.argv[1] == "-s": 101 base = int(sys.argv[2]) 102 i = 3 103 else: 104 base = 0 105 i = 1 106 for sector, filename in enumerate(sys.argv[i:]): 107 upload(filename, sector + base) 108 sleep(5) # give the device a rest 109 else: 110 print >>sys.stderr, sys.argv[0], "-i | <filename>..." 111 sys.exit(1) 112 finally: 113 closePort() 114 115 # vim: tabstop=4 expandtab shiftwidth=4