diff options
-rwxr-xr-x | downloader/downloader.py | 49 |
1 files changed, 15 insertions, 34 deletions
diff --git a/downloader/downloader.py b/downloader/downloader.py index b332271..8da13cf 100755 --- a/downloader/downloader.py +++ b/downloader/downloader.py @@ -80,42 +80,24 @@ def open_serial(device, baud): import os import tty import termios + import serial print "opening %s (%s Baud)" % (device, baud) - baudrates = { 50: termios.B50, 75: termios.B75, 110: termios.B110, 134: termios.B134, - 150: termios.B150, 200: termios.B200, 300: termios.B300, 600: termios.B600, - 1200: termios.B1200, 1800: termios.B1800, 2400: termios.B2400, 4800: termios.B4800, - 9600: termios.B9600, 19200: termios.B19200, 38400: termios.B38400, - 57600: termios.B57600, 115200: termios.B115200, 230400: termios.B230400 } - - baudreate = termios.B57600 try: - baudrate = baudrates[int(baud)] - except (KeyError, ValueError): - print "ERROR: invalid baudrate" - sys.exit(3) - - try: - dev = os.open(device, os.O_RDWR | os.O_NOCTTY) - tty.setraw(dev, termios.TCSAFLUSH) - tio = termios.tcgetattr(dev) - tio[4] = tio[5] = baudrate - termios.tcsetattr(dev, termios.TCSAFLUSH, tio) - termios.tcflush(dev, termios.TCIFLUSH) + dev = serial.Serial(port=device, baudrate=baud) + dev.flushInput() + dev.flushOutput() return dev - except OSError, msg: + except (ValueError, serial.SerialException), msg: print "ERROR: opening serial device: %s" % msg sys.exit(3) - except termios.error, msg: - print "ERROR: configuring serial device: %s" % msg - sys.exit(3) def calc_csum(str): cs = 0 for c in str: - cs ^= ord(c) + cs ^= c return cs def exec_command(dev, cmd, answer): @@ -126,18 +108,18 @@ def exec_command(dev, cmd, answer): 5: "address invalid", 6: "address prohibited", 7: "value out of bounds" } - cstr = cmd + chr(calc_csum(cmd)) - os.write(dev, cstr) + cstr = bytearray(cmd) + cstr.extend(struct.pack("<B", calc_csum(cstr))) + dev.write(cstr) - astr = b'' - while len(astr) < 3: - astr += os.read(dev, 3 - len(astr)) + astr = bytearray() + astr += dev.read(3) - if astr[0] != cmd[0]: + if astr[0] != cstr[0]: print "ERROR: bootloader returned wrong command code" sys.exit(4) - ret = ord(astr[1]) + ret = astr[1] if ret != 0: rstr = "invalid return code" try: @@ -147,9 +129,8 @@ def exec_command(dev, cmd, answer): print "ERROR: bootloader returned %d: %s" % (ret, rstr) sys.exit(4) - answer_len = struct.calcsize(answer) + len(astr) - while len(astr) < answer_len: - astr += os.read(dev, answer_len - len(astr)) + answer_len = struct.calcsize(answer) + astr += dev.read(answer_len) if 0 != calc_csum(astr): print "ERROR: checksum error" |