def eraseUserFlash(self): returnValue = True reply = self.sendCommand('ERASE', [[255]], timeout=5) if reply != [ACK, ACK]: errorMessage(('Unexpected reply %s\n' % repr(reply))) returnValue = False return returnValue
def _addWall(self, T, line): maxX = (self.size)[1] maxY = (self.size)[0] if (_isHorizontal(line)): rd = line[1] ru = rd - 1 if (rd > 0 and rd < maxX): for i in range(line[0], line[2]): T.append((((ru, i), par.d, (rd, i)), 0.0)) T.append((((ru, i), par.d, (ru, i)), 1.0)) T.append((((rd, i), par.u, (ru, i)), 0.0)) T.append((((rd, i), par.u, (rd, i)), 1.0)) elif (_isVertical(line)): cr = line[0] cl = cr - 1 if (cr > 0 and cr < maxY): for i in range(line[1], line[3]): T.append((((i, cl), par.r, (i, cr)), 0.0)) T.append((((i, cl), par.r, (i, cl)), 1.0)) T.append((((i, cr), par.l, (i, cl)), 0.0)) T.append((((i, cr), par.l, (i, cr)), 1.0)) else: mes.errorMessage("cannot recognise wall") return T
def runBootloader(self): returnValue = None reply = self.sendCommand(self.RUN_BOOTLOADER, [], True) if reply: commandReturnValue = (reply[2]) time.sleep(TIMEOUT_TO_SWITCH_BETWEEN_APPLICATION_AND_BOOTLOADER) for i in range(5): try: self.serialPort = serial.Serial( port=self.bootloaderPort, baudrate=BOOTLOADER_COMMAND_BAUDRATE, timeout=1) self.serialPort = checkSerialPort(self.bootloaderPort, self.serialPort) time.sleep(0.5) self.serialPort.flushInput() if self.serialPort is None: returnValue = None else: returnValue = commandReturnValue break except Exception, inst: errorMessage((' '.join(repr(a) for a in inst.args) + '\n')) time.sleep(0.5) continue
def upgradeFirmwareVersion(self, filename=None): returnValue = True if filename is None: filename = self.firmwareName if returnValue: firmwareType = self.getFirmwareType() if firmwareType == self.APP_RUNNING: reply = self.runBootloader() if reply is None: returnValue = False else: if firmwareType == self.BL_RUNNING: pass else: returnValue = False if returnValue: if self.getFirmwareType() != self.BL_RUNNING: errorMessage( 'Unable to read from port, please use a USB HUB 1.1 and rerun the command\n' ) returnValue = False else: reply = self.sendCommand(self.DOWNLOAD_IMAGE, [filename]) returnValue = (reply[2]) == self.OK return returnValue
def openPort(self): error = 0 try: self.serialPort = serial.Serial(port=self.port, bytesize=8, baudrate=115200, parity='N', timeout=0) except: errorMessage((('Trouble opening port : ' + repr(self.port)) + '\n')) error = 1 return error
def checkSerialPort(portName, serialPort): returnValue = serialPort try: serialPort.write(' ') except serial.serialutil.SerialException, inst: errorMessage((' '.join(repr(a) for a in inst.args) + '\n')) infoMessage('Write to serial port failed: please try a different USB port or a USB hub 1.1\n') returnValue = None
def open(self): error = 0 try: self.serialPort = serial.Serial(port=self.port, baudrate=BOOTLOADER_COMMAND_BAUDRATE, timeout=1) time.sleep(0.10000000000000001) self.serialPort.flushInput() except: errorMessage((('Trouble opening port : ' + repr(self.port)) + '\n')) error = 1 return error
def startApplication(self, startAddress=134217728): returnValue = True if (self.startAddress is not None and startAddress != 0): startAddress = self.startAddress arg1 = u32ToArray(startAddress) arg1.reverse() reply = self.sendCommand('GO', [arg1]) if reply != [ACK, ACK, ACK]: errorMessage(('\n\nUnexpected reply %s\n' % repr(reply))) returnValue = False return returnValue
def init(self, checkFirmwareImage=True): error = 0 if self.noReset: if self.rfMode: error = self.reset(False) time.sleep(0.10000000000000001) else: error = 0 else: error = self.reset(True, checkFirmwareImage) if error == 1: errorMessage((('Trouble while resetting board on port : ' + repr(self.port)) + '\n')) if error == 0: error = self.openPort() if error == 0: if self.rfMode: self.packetSize = 96 def sendBinary(port, data, length): for i in range(length): port.write(chr(((data >> (i * 8)) & 255))) continue sendBinary(self.serialPort, self.eui64, 8) sendBinary(self.serialPort, 45067, 2) sendBinary(self.serialPort, 15, 1) time.sleep(0.5) while self.serialPort.inWaiting() > 0: sys.stdout.write( self.serialPort.read(self.serialPort.inWaiting())) continue else: self.packetSize = 256 self.STBL = STBL(self.serialPort, packetSize=self.packetSize, serialMode=(not self.rfMode)) if self.STBL is not None: tmp = self.STBL.bootloaderInit() if tmp: pass else: error = 1 return error
def enableReadProtection(self, enable): returnValue = True if enable == False: reply = self.sendCommand('READOUT_UNPROTECT') if reply != [ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join( ('%02x' % a) for a in reply)) + ') \n')) returnValue = False else: item0, item1 = self.memoryRead(134481920, 512) returnValue = item0 cibData = item1 if returnValue: reply = self.sendCommand('ERASE', [[254]], timeout=5) if reply != [ACK, ACK]: errorMessage(('Unexpected reply %s\n' % repr(reply))) returnValue = False if returnValue: arg1 = u32ToArray(134481922) arg1.reverse() packet = cibData[2:256] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join( ('%02x' % a) for a in reply)) + ') \n')) returnValue = False if returnValue: arg1 = u32ToArray(134482176) arg1.reverse() packet = cibData[256:] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join( ('%02x' % a) for a in reply)) + ') \n')) returnValue = False if returnValue: reply = self.sendCommand('READOUT_PROTECT') if reply != [ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join( ('%02x' % a) for a in reply)) + ') \n')) returnValue = False return returnValue
def runFirmware(self): returnValue = None reply = self.sendCommand(self.RUN_APPLICATION, [], True) if reply: commandReturnValue = (reply[2]) time.sleep(TIMEOUT_TO_SWITCH_BETWEEN_APPLICATION_AND_BOOTLOADER) for i in range(5): try: self.serialPort = serial.Serial(port=self.port, baudrate=BOOTLOADER_COMMAND_BAUDRATE, timeout=1) self.serialPort = checkSerialPort(self.port, self.serialPort) if self.serialPort is None: returnValue = None else: returnValue = commandReturnValue break except Exception, inst: errorMessage((' '.join(repr(a) for a in inst.args) + '\n')) time.sleep(0.5) continue
def memoryRead(self, address, size): returnValue = True currentSize = 0 memRead = [] while (returnValue and currentSize < size): packet_size = min(self.packetSize, (size - currentSize)) arg1 = u32ToArray((address + currentSize)) arg1.reverse() reply = self.sendCommand('READ', [arg1, [(packet_size - 1)]]) if reply == [NAK]: returnValue = False else: if reply[:3] != [ACK, ACK, ACK]: errorMessage(('\n\nXXUnexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) returnValue = False else: memRead = (memRead + reply[3:]) currentSize = (currentSize + packet_size) continue return (returnValue, memRead)
def programCibData(self, cibData): returnValue = True if returnValue: reply = self.sendCommand('ERASE', [[254]], timeout=5) if reply != [ACK, ACK]: errorMessage(('Unexpected reply %s\n' % repr(reply))) returnValue = False if returnValue: arg1 = u32ToArray(134481920) arg1.reverse() packet = cibData[:256] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join( ('%02x' % a) for a in reply)) + ') \n')) returnValue = False if returnValue: arg1 = u32ToArray(134482176) arg1.reverse() packet = cibData[256:] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join( ('%02x' % a) for a in reply)) + ') \n')) returnValue = False return returnValue
def enableReadProtection(self, enable): returnValue = True if enable == False: reply = self.sendCommand('READOUT_UNPROTECT') if reply != [ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join(('%02x' % a) for a in reply)) + ') \n')) returnValue = False else: item0, item1 = self.memoryRead(134481920, 512) returnValue = item0 cibData = item1 if returnValue: reply = self.sendCommand('ERASE', [[254]], timeout=5) if reply != [ACK, ACK]: errorMessage(('Unexpected reply %s\n' % repr(reply))) returnValue = False if returnValue: arg1 = u32ToArray(134481922) arg1.reverse() packet = cibData[2:256] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join(('%02x' % a) for a in reply)) + ') \n')) returnValue = False if returnValue: arg1 = u32ToArray(134482176) arg1.reverse() packet = cibData[256:] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join(('%02x' % a) for a in reply)) + ') \n')) returnValue = False if returnValue: reply = self.sendCommand('READOUT_PROTECT') if reply != [ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join(('%02x' % a) for a in reply)) + ') \n')) returnValue = False return returnValue
def programCibData(self, cibData): returnValue = True if returnValue: reply = self.sendCommand('ERASE', [[254]], timeout=5) if reply != [ACK, ACK]: errorMessage(('Unexpected reply %s\n' % repr(reply))) returnValue = False if returnValue: arg1 = u32ToArray(134481920) arg1.reverse() packet = cibData[:256] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join(('%02x' % a) for a in reply)) + ') \n')) returnValue = False if returnValue: arg1 = u32ToArray(134482176) arg1.reverse() packet = cibData[256:] packet = ([(len(packet) - 1)] + packet) reply = self.sendCommand('WRITE', [arg1, packet], 5) if reply != [ACK, ACK, ACK]: errorMessage((('Unexpected reply (' + ','.join(('%02x' % a) for a in reply)) + ') \n')) returnValue = False return returnValue
def init(self, checkFirmwareImage=True): error = 0 if self.noReset: if self.rfMode: error = self.reset(False) time.sleep(0.10000000000000001) else: error = 0 else: error = self.reset(True, checkFirmwareImage) if error == 1: errorMessage((('Trouble while resetting board on port : ' + repr(self.port)) + '\n')) if error == 0: error = self.openPort() if error == 0: if self.rfMode: self.packetSize = 96 def sendBinary(port, data, length): for i in range(length): port.write(chr(((data >> (i * 8)) & 255))) continue sendBinary(self.serialPort, self.eui64, 8) sendBinary(self.serialPort, 45067, 2) sendBinary(self.serialPort, 15, 1) time.sleep(0.5) while self.serialPort.inWaiting() > 0: sys.stdout.write(self.serialPort.read(self.serialPort.inWaiting())) continue else: self.packetSize = 256 self.STBL = STBL(self.serialPort, packetSize=self.packetSize, serialMode=(not self.rfMode)) if self.STBL is not None: tmp = self.STBL.bootloaderInit() if tmp: pass else: error = 1 return error
def upgradeFirmwareVersion(self, filename=None): returnValue = True if filename is None: filename = self.firmwareName if returnValue: firmwareType = self.getFirmwareType() if firmwareType == self.APP_RUNNING: reply = self.runBootloader() if reply is None: returnValue = False else: if firmwareType == self.BL_RUNNING: pass else: returnValue = False if returnValue: if self.getFirmwareType() != self.BL_RUNNING: errorMessage('Unable to read from port, please use a USB HUB 1.1 and rerun the command\n') returnValue = False else: reply = self.sendCommand(self.DOWNLOAD_IMAGE, [filename]) returnValue = (reply[2]) == self.OK return returnValue
def bootloaderInit(self): returnValue = True if (returnValue and self.serialMode): reply = None if self.verbose: infoMessage('Sending byte 7f\n') self.serialPort.write(struct.pack('B', 127)) startTime = time.time() while (self.serialPort.inWaiting() == 0 and (time.time() - startTime) < 1): continue r = self.serialPort.read(1) if r: reply = struct.unpack(('B' * len(r)), r) else: reply = None if self.verbose: infoMessage(("Reply received '%s'\n" % hexString(reply))) if reply == None: errorMessage('No reply received\n') returnValue = False else: if (reply[0]) != ACK: errorMessage(('Unexpected reply %s\n' % hexString(reply))) returnValue = False if returnValue: reply = self.sendCommand('GET', [], 2) if (len(reply) < 4 or ((reply[0]) != ACK or (reply[-1]) != ACK)): errorMessage(('Unexpected reply %s\n' % hexString(reply))) returnValue = False else: if self.verbose: infoMessage( ('Bootloader version %d.%d\n' % (((reply[2]) & 15), ((reply[2]) >> 4)))) if returnValue: reply = self.sendCommand('GET_ID') if (len(reply) == 0 or ((reply[0]) != ACK or (reply[-1]) != ACK)): errorMessage(('Unexpected reply %s\n' % hexString(reply))) returnValue = False else: if self.verbose: infoMessage((('Product ID = 0x' + ''.join( ('%02X' % a) for a in reply[2:-1])) + '\n')) return returnValue
def __init__(self, size, lines, rewardSet, startingState=0): if (not (isinstance(size, tuple)) or not (isinstance(rewardSet, list))): mes.errorMessage( "cannot match size/reward setting/transition setting type") del self return mes.settingMessage("number of action(s)") self.numActions = 4 mes.setMessage("number of action(s)") mes.settingMessage("number of dimension(s)") self.dimensions = len(size) mes.setMessage("number of dimension(s)") mes.settingMessage("dimensions intervals (upper boundaries)") self.size = size mes.setMessage("dimensions intervals (upper boundaries)") mes.settingMessage("starting state") self._startingState = startingState mes.setMessage("starting state") self._resetModel() if (self.dimensions > par.maxDim or self.dimensions < par.minDim): mes.errorMessage( "not supportable dimension(s). Should be between 1 and 3") del self return mes.settingMessage("number of states") self.numStates = 1 for i in range(0, self.dimensions): self.numStates *= self.size[i] mes.setMessage("number of states") mes.settingMessage("basic transitions") transitionSet = self._predefTransSet() mes.settingMessage("basic transitions") mes.settingMessage("maze transitions") transitionSet = self._generateT(lines, transitionSet) mes.settingMessage("maze transitions") mes.settingMessage( "reward table and transition probabilistic distribution") if (self._setR(rewardSet) == -1 or self._setT(transitionSet) == -1): mes.errorMessage("incorrect reward/transition setting") del self return mes.setMessage( "reward table and transition probabilistic distribution")
def bootloaderInit(self): returnValue = True if (returnValue and self.serialMode): reply = None if self.verbose: infoMessage('Sending byte 7f\n') self.serialPort.write(struct.pack('B', 127)) startTime = time.time() while (self.serialPort.inWaiting() == 0 and (time.time() - startTime) < 1): continue r = self.serialPort.read(1) if r: reply = struct.unpack(('B' * len(r)), r) else: reply = None if self.verbose: infoMessage(("Reply received '%s'\n" % hexString(reply))) if reply == None: errorMessage('No reply received\n') returnValue = False else: if (reply[0]) != ACK: errorMessage(('Unexpected reply %s\n' % hexString(reply))) returnValue = False if returnValue: reply = self.sendCommand('GET', [], 2) if (len(reply) < 4 or ((reply[0]) != ACK or (reply[-1]) != ACK)): errorMessage(('Unexpected reply %s\n' % hexString(reply))) returnValue = False else: if self.verbose: infoMessage(('Bootloader version %d.%d\n' % (((reply[2]) & 15), ((reply[2]) >> 4)))) if returnValue: reply = self.sendCommand('GET_ID') if (len(reply) == 0 or ((reply[0]) != ACK or (reply[-1]) != ACK)): errorMessage(('Unexpected reply %s\n' % hexString(reply))) returnValue = False else: if self.verbose: infoMessage((('Product ID = 0x' + ''.join(('%02X' % a) for a in reply[2:-1])) + '\n')) return returnValue
if (options.interface == "rs232") and (options.port == None): parser.print_help() sys.exit(-1) if options.interface != "rs232" and options.interface != "jlink": parser.print_help() sys.exit(-1) startAddress = int(options.address, 16) if options.interface == "rs232": optionArg = options.port.upper() if optionArg == "AUTO": port = getFirstAvailableSerialPort() if port is None: errorMessage("Unable to find serial port in auto mode: no STM32W boards detected\n") sys.exit(-1) infoMessage("Auto mode selected serial port: %s\n" % port) elif options.port[:4] == "/dev": ## For Linux port = options.port else: try: port = int(optionArg) except ValueError: errorMessage("Invalid port: %s\n" % options.port) sys.exit(-1) else: port = None if options.interface == "jlink": errorMessage("JLink not yet supported.\n")
parser.print_help() sys.exit(-1) if (options.interface != "rs232" and options.interface != "jlink"): parser.print_help() sys.exit(-1) startAddress = int(options.address, 16) if (options.interface == "rs232"): optionArg = options.port.upper() if (optionArg == "AUTO"): port = getFirstAvailableSerialPort() if port is None: errorMessage( "Unable to find serial port in auto mode: no STM32W boards detected\n" ) sys.exit(-1) infoMessage("Auto mode selected serial port: %s\n" % port) elif (options.port[:4] == "/dev"): ## For Linux port = options.port else: try: port = int(optionArg) except ValueError: errorMessage("Invalid port: %s\n" % options.port) sys.exit(-1) else: port = None if (options.interface == "jlink"):
def loadFile(self, name): returnValue = True state = self.STATE_WAITING_CRC16 filename = os.path.basename(name) startTime = time.time() try: f = open(name, 'rb') infoMessage((('File ' + name) + ' opened\n')) f.seek(0, 2) file_size = f.tell() f.seek(0, 0) packet_number = 0 loop_counter = 1 size = file_size retry = 0 packet = [] prevState = self.STATE_READY while True: newState = state if state == self.STATE_WAITING_CRC16: if self.updateAction: self.updateAction((file_size - max(size, 0)), file_size) data = self.getByte() if data == self.CRC16: newState = self.STATE_READY else: if state == self.STATE_WAITING_ACK: if self.updateAction: self.updateAction((file_size - max(size, 0)), file_size) data = self.getByte() if data is not None: if data == self.ACK: if prevState == self.STATE_READY: retry = 0 if loop_counter > 1: size = (size - packet_size) packet_number = ((packet_number + 1) % 256) loop_counter = (loop_counter + 1) packet_done = True if self.updateAction: self.updateAction( (file_size - max(size, 0)), file_size) else: infoMessage( ('Sent %05d/%05d\r' % ((file_size - max(size, 0)), file_size))) newState = self.STATE_READY else: if prevState == self.STATE_SEND_EOT: newState = self.STATE_SEND_SESSION_DONE else: if prevState == self.STATE_SEND_SESSION_DONE: newState = self.STATE_START_APPLICATION else: if data == self.CA: errorMessage( 'Transaction aborted by client\n') newState = self.STATE_DONE else: if data == self.CRC16: pass else: if prevState == self.STATE_READY: infoMessage('Retrying\n') retry = (retry + 1) if retry > 3: errorMessage( 'Too many retry exiting\n') newState = self.STATE_DONE else: newState = self.STATE_READY else: if state == self.STATE_READY: if size <= 0: newState = self.STATE_SEND_EOT else: if retry == 0: packet = [] if loop_counter == 1: packet.extend( struct.unpack( ('%uB' % len(filename)), filename)) packet = (packet + [0]) size_string = ('%d ' % file_size) packet.extend( struct.unpack( ('%uB' % len(size_string)), size_string)) packet_size = self.PACKET_SIZE else: packet_size = self.PACKET_1K_SIZE packet_string = f.read(packet_size) packet.extend( struct.unpack( ('%uB' % len(packet_string)), packet_string)) packet = (packet + ([0] * (packet_size - len(packet)))) if self.sendYModemPacket( packet, packet_number): newState = self.STATE_DONE else: newState = self.STATE_WAITING_ACK else: if state == self.STATE_SEND_EOT: if self.updateAction: self.updateAction( (file_size - max(size, 0)), file_size) else: infoMessage(('Sent %05d/%05d\r' % ((file_size - max(size, 0)), file_size))) self.sendByte(self.EOT) newState = self.STATE_WAITING_ACK else: if state == self.STATE_SEND_SESSION_DONE: self.sendYModemPacket(([0] * 128), 0) newState = self.STATE_WAITING_ACK else: if state == self.STATE_START_APPLICATION: self.startApplication() newState = self.STATE_DONE else: if state == self.STATE_DONE: returnValue = False endTime = time.time() infoMessage('\nDone\n') break else: errorMessage( ('Unknonw state = %d' % state)) newState = self.STATE_DONE if state != newState: prevState = state state = newState continue else: continue return returnValue except: errorMessage((('File ' + name) + ' open failed\n')) if self.updateAction: self.updateAction(0, 0) return returnValue
def reset(self, bootloader=False, checkSTM32FFirmware=True): returnValue = 0 if self.portType == 'FTDI': self.portHandle.reset(bootloader) else: if self.portType == 'STM32': returnValue = self.portHandle.open() if checkSTM32FFirmware: if returnValue == 0: firmwareVersionCurrent = self.portHandle.getFirmwareVersionFromFile( stringMode=False) if returnValue == 0: firmwareType = self.portHandle.getFirmwareType() if (firmwareType is None or (firmwareType != self.portHandle.BL_RUNNING and firmwareType != self.portHandle.APP_RUNNING)): errorMessage( 'Failed to get firmware type: Invalid reply\n') returnValue = 1 if returnValue == 0: firmwareVersion = self.portHandle.getFirmwareVersion() if firmwareVersion is None: errorMessage( 'Failed to get firmware version:Invalid reply\n' ) returnValue = 1 else: if (firmwareVersion & 4278190080L): firmwareVersion = self.portHandle.FIRMWARE_VERSION_NONE if returnValue == 0: bootloaderFirmwareVersion = self.portHandle.getBootloaderFirmwareVersion( ) if bootloaderFirmwareVersion is None: errorMessage( 'Failed to get bootloader firmware version:Invalid reply\n' ) returnValue = 1 if bootloaderFirmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE: self.portHandle.bootloaderPort = self.portHandle.mapSTMCompositeComPortToBootloaderCOMPort( self.portHandle.port) if returnValue == 0: if (firmwareType == self.portHandle.BL_RUNNING and (firmwareVersion != self.portHandle.FIRMWARE_VERSION_NONE and firmwareVersion >= firmwareVersionCurrent)): if bootloaderFirmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE: errorMessage( 'Please unplug and replug the board to the PC\n' ) returnValue = 2 else: result = self.portHandle.runFirmware() if result is not self.portHandle.OK: errorMessage( 'Failed to run firmware: Invalid reply\n' ) returnValue = 1 if returnValue == 0: if (firmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE or firmwareVersion < firmwareVersionCurrent): if firmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE: infoMessage(( 'Missing STM32F103 firmware, upgrading to version %s\n' % self.portHandle.getFirmwareVersionFromFile( stringMode=True))) else: infoMessage(( 'Old STM32F103 firmware version %s, upgrading to version %s\n' % (self.portHandle.versionInStringFormat( firmwareVersion), self.portHandle. getFirmwareVersionFromFile( stringMode=True)))) warningMessage( 'Changing firmware version can break backward compatibility and older version of stm32w_flasher may not work\n' ) if self.portHandle.upgradeFirmwareVersion(): if ((firmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE or firmwareVersion < 131072) and firmwareVersionCurrent >= 131072): errorMessage(( 'Switching to firmware %s may change your COM port number, please unplug and replug your USB device and re-run this command again\n' % self.portHandle. getFirmwareVersionFromFile( stringMode=True))) returnValue = 2 else: result = self.portHandle.runFirmware() if result is not self.portHandle.OK: errorMessage( 'Failed to run firmware: Invalid reply\n' ) returnValue = 1 else: errorMessage( 'Failed to upgrade firmware version: Invalid reply\n' ) returnValue = 1 if returnValue == 0: firmwareVersion = self.portHandle.getFirmwareVersion() if firmwareVersion is None: errorMessage('Invalid reply\n') returnValue = 1 if returnValue == 0: if firmwareVersion >= 131076: if self.portHandle.isBootloaderFirmwareVersionOld( ): infoMessage( 'Upgrading STM32F Bootloader firmware\n') if self.portHandle.upgradeBootloaderFirmwareVersion( ): pass else: errorMessage( 'Upgrade of the STM32F bootloader failed. This is a CRITICAL error and your board may brick your board\n' ) returnValue = 1 if returnValue == 0: if firmwareVersion > firmwareVersionCurrent: warningMessage( 'Device firmware is more recent than expected. Are you using an old version of this software ?\n' ) if returnValue == 0: result = self.portHandle.reset(bootloader) if result is None: errorMessage('Failed to reset STM32W: Invalid reply\n') returnValue = 1 self.portHandle.close() else: errorMessage( ('Failed to detect port type for %s\n' % self.port)) returnValue = 1 return returnValue
def reset(self, bootloader=False, checkSTM32FFirmware=True): returnValue = 0 if self.portType == 'FTDI': self.portHandle.reset(bootloader) else: if self.portType == 'STM32': returnValue = self.portHandle.open() if checkSTM32FFirmware: if returnValue == 0: firmwareVersionCurrent = self.portHandle.getFirmwareVersionFromFile(stringMode=False) if returnValue == 0: firmwareType = self.portHandle.getFirmwareType() if (firmwareType is None or (firmwareType != self.portHandle.BL_RUNNING and firmwareType != self.portHandle.APP_RUNNING)): errorMessage('Failed to get firmware type: Invalid reply\n') returnValue = 1 if returnValue == 0: firmwareVersion = self.portHandle.getFirmwareVersion() if firmwareVersion is None: errorMessage('Failed to get firmware version:Invalid reply\n') returnValue = 1 else: if (firmwareVersion & 4278190080L): firmwareVersion = self.portHandle.FIRMWARE_VERSION_NONE if returnValue == 0: bootloaderFirmwareVersion = self.portHandle.getBootloaderFirmwareVersion() if bootloaderFirmwareVersion is None: errorMessage('Failed to get bootloader firmware version:Invalid reply\n') returnValue = 1 if bootloaderFirmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE: self.portHandle.bootloaderPort = self.portHandle.mapSTMCompositeComPortToBootloaderCOMPort(self.portHandle.port) if returnValue == 0: if (firmwareType == self.portHandle.BL_RUNNING and (firmwareVersion != self.portHandle.FIRMWARE_VERSION_NONE and firmwareVersion >= firmwareVersionCurrent)): if bootloaderFirmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE: errorMessage('Please unplug and replug the board to the PC\n') returnValue = 2 else: result = self.portHandle.runFirmware() if result is not self.portHandle.OK: errorMessage('Failed to run firmware: Invalid reply\n') returnValue = 1 if returnValue == 0: if (firmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE or firmwareVersion < firmwareVersionCurrent): if firmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE: infoMessage(('Missing STM32F103 firmware, upgrading to version %s\n' % self.portHandle.getFirmwareVersionFromFile(stringMode=True))) else: infoMessage(('Old STM32F103 firmware version %s, upgrading to version %s\n' % (self.portHandle.versionInStringFormat(firmwareVersion), self.portHandle.getFirmwareVersionFromFile(stringMode=True)))) warningMessage('Changing firmware version can break backward compatibility and older version of stm32w_flasher may not work\n') if self.portHandle.upgradeFirmwareVersion(): if ((firmwareVersion == self.portHandle.FIRMWARE_VERSION_NONE or firmwareVersion < 131072) and firmwareVersionCurrent >= 131072): errorMessage(('Switching to firmware %s may change your COM port number, please unplug and replug your USB device and re-run this command again\n' % self.portHandle.getFirmwareVersionFromFile(stringMode=True))) returnValue = 2 else: result = self.portHandle.runFirmware() if result is not self.portHandle.OK: errorMessage('Failed to run firmware: Invalid reply\n') returnValue = 1 else: errorMessage('Failed to upgrade firmware version: Invalid reply\n') returnValue = 1 if returnValue == 0: firmwareVersion = self.portHandle.getFirmwareVersion() if firmwareVersion is None: errorMessage('Invalid reply\n') returnValue = 1 if returnValue == 0: if firmwareVersion >= 131076: if self.portHandle.isBootloaderFirmwareVersionOld(): infoMessage('Upgrading STM32F Bootloader firmware\n') if self.portHandle.upgradeBootloaderFirmwareVersion(): pass else: errorMessage('Upgrade of the STM32F bootloader failed. This is a CRITICAL error and your board may brick your board\n') returnValue = 1 if returnValue == 0: if firmwareVersion > firmwareVersionCurrent: warningMessage('Device firmware is more recent than expected. Are you using an old version of this software ?\n') if returnValue == 0: result = self.portHandle.reset(bootloader) if result is None: errorMessage('Failed to reset STM32W: Invalid reply\n') returnValue = 1 self.portHandle.close() else: errorMessage(('Failed to detect port type for %s\n' % self.port)) returnValue = 1 return returnValue
def loadFile(self, inputFile=None, startAddress=None, progressReport=None, doErase=True): if inputFile is not None: self.inputFile = inputFile if startAddress is not None: self.startAddress = startAddress returnValue = True f = fileFormatReader(self.inputFile, self.startAddress) try: item0, item1 = f.getRawBinary() self.startAddress = item0 file_content = item1 except IOError: errorMessage((('File ' + self.inputFile) + ' open failed\n')) returnValue = False if returnValue: file_size = len(file_content) packet = [] address = self.startAddress pages = int(((file_size + 1023) / 1024)) startPage = (((self.startAddress & 4294966272L) - 134217728) / 1024) eraseArg = ([(pages - 1)] + range(startPage, (startPage + pages), 1)) infoMessage(('Erasing pages from %d to %d...' % (startPage, ((startPage + pages) - 1)))) if ('STM32W_FLASHER_JLINK_DONT_ERASE' in os.environ or (not doErase)): infoMessage('(skipped)', False) else: reply = self.sendCommand('ERASE', [eraseArg], timeout=10) if reply != [ACK, ACK]: errorMessage(('Unexpected reply %s\n' % repr(reply))) returnValue = False if returnValue: infoMessage('done\n', False) size = 0 while returnValue: packet = [] packet_size = self.packetSize packet_string = file_content[size:(size + packet_size)] packet_size = len(packet_string) if packet_size == 0: infoMessage('\n') break else: size = (size + packet_size) packet.extend(packet_string) if (len(packet) % 2) != 0: packet = (packet + [255]) packet = ([(len(packet) - 1)] + packet) if progressReport: progressReport(size, file_size) else: infoMessage( ('Programming %05d/%05d\r' % (size, file_size))) arg1 = u32ToArray(address) arg1.reverse() if (self.serialMode or size == packet_size): reply = self.sendCommand('WRITE', [arg1, packet]) if reply != [ACK, ACK, ACK]: errorMessage( ('\n\n+Unexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) returnValue = False else: retries = 0 MAX_RETRIES = 3 while returnValue: reply = self.sendCommand('WRITE_INCREMENTAL', [packet]) if reply != [ACK, ACK]: retries = (retries + 1) if retries > MAX_RETRIES: errorMessage(( '\n\nUnexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) returnValue = False break else: errorMessage(( '\n\nUnexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) infoMessage('Retrying...\n') continue else: break address = (address + packet_size) continue if returnValue: if progressReport == None: infoMessage('Done\n') return returnValue
def verifyFile(self, inputFile=None, startAddress=None, progressReport=None): if inputFile is not None: self.inputFile = inputFile if startAddress is not None: self.startAddress = startAddress returnValue = True f = fileFormatReader(self.inputFile, self.startAddress) try: item0, item1 = f.getRawBinary() self.startAddress = item0 file_content = item1 except IOError: errorMessage((('File ' + self.inputFile) + ' open failed\n')) returnValue = False if returnValue: file_size = len(file_content) packet = [] address = self.startAddress size = 0 errors = 0 while returnValue: packet = [] packet_size = self.packetSize packet_string = file_content[size:(size + packet_size)] packet_size = len(packet_string) if packet_size == 0: infoMessage('\n') break else: size = (size + packet_size) packet.extend(packet_string) if progressReport: progressReport(size, file_size) else: infoMessage(('Verifying %05d/%05d\r' % (size, file_size))) arg1 = u32ToArray(address) arg1.reverse() reply = self.sendCommand('READ', [arg1, [(len(packet) - 1)]]) if reply[:3] != [ACK, ACK, ACK]: errorMessage(('\n\nUnexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) returnValue = False if len(reply[3:]) != len(packet): errorMessage(( 'Invalid data read, expected length = %d, received bytes = %d\n' % (len(packet), len(reply[3:])))) returnValue = False if (returnValue and reply[3:] != packet): returnValue = False infoMessage('Verify failed \n') infoMessage( ('%-8s: %5s %5s\n' % ('Addr', 'Flash', 'file'))) for i in range(len(packet)): if (reply[(3 + i)]) != (packet[i]): infoMessage( ('%08x: %02x %02x\n' % ((address + i), (reply[(i + 3)]), (packet[i])))) errors = (errors + 1) if errors > 64: break else: continue else: continue address = (address + packet_size) continue if returnValue: if progressReport == None: infoMessage('Done\n') return returnValue
def verifyFile(self, inputFile=None, startAddress=None, progressReport=None): if inputFile is not None: self.inputFile = inputFile if startAddress is not None: self.startAddress = startAddress returnValue = True f = fileFormatReader(self.inputFile, self.startAddress) try: item0, item1 = f.getRawBinary() self.startAddress = item0 file_content = item1 except IOError: errorMessage((('File ' + self.inputFile) + ' open failed\n')) returnValue = False if returnValue: file_size = len(file_content) packet = [] address = self.startAddress size = 0 errors = 0 while returnValue: packet = [] packet_size = self.packetSize packet_string = file_content[size:(size + packet_size)] packet_size = len(packet_string) if packet_size == 0: infoMessage('\n') break else: size = (size + packet_size) packet.extend(packet_string) if progressReport: progressReport(size, file_size) else: infoMessage(('Verifying %05d/%05d\r' % (size, file_size))) arg1 = u32ToArray(address) arg1.reverse() reply = self.sendCommand('READ', [arg1, [(len(packet) - 1)]]) if reply[:3] != [ACK, ACK, ACK]: errorMessage(('\n\nUnexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) returnValue = False if len(reply[3:]) != len(packet): errorMessage(('Invalid data read, expected length = %d, received bytes = %d\n' % (len(packet), len(reply[3:])))) returnValue = False if (returnValue and reply[3:] != packet): returnValue = False infoMessage('Verify failed \n') infoMessage(('%-8s: %5s %5s\n' % ('Addr', 'Flash', 'file'))) for i in range(len(packet)): if (reply[(3 + i)]) != (packet[i]): infoMessage(('%08x: %02x %02x\n' % ((address + i), (reply[(i + 3)]), (packet[i])))) errors = (errors + 1) if errors > 64: break else: continue else: continue address = (address + packet_size) continue if returnValue: if progressReport == None: infoMessage('Done\n') return returnValue
def loadFile(self, name): returnValue = True state = self.STATE_WAITING_CRC16 filename = os.path.basename(name) startTime = time.time() try: f = open(name, 'rb') infoMessage((('File ' + name) + ' opened\n')) f.seek(0, 2) file_size = f.tell() f.seek(0, 0) packet_number = 0 loop_counter = 1 size = file_size retry = 0 packet = [] prevState = self.STATE_READY while True: newState = state if state == self.STATE_WAITING_CRC16: if self.updateAction: self.updateAction((file_size - max(size, 0)), file_size) data = self.getByte() if data == self.CRC16: newState = self.STATE_READY else: if state == self.STATE_WAITING_ACK: if self.updateAction: self.updateAction((file_size - max(size, 0)), file_size) data = self.getByte() if data is not None: if data == self.ACK: if prevState == self.STATE_READY: retry = 0 if loop_counter > 1: size = (size - packet_size) packet_number = ((packet_number + 1) % 256) loop_counter = (loop_counter + 1) packet_done = True if self.updateAction: self.updateAction((file_size - max(size, 0)), file_size) else: infoMessage(('Sent %05d/%05d\r' % ((file_size - max(size, 0)), file_size))) newState = self.STATE_READY else: if prevState == self.STATE_SEND_EOT: newState = self.STATE_SEND_SESSION_DONE else: if prevState == self.STATE_SEND_SESSION_DONE: newState = self.STATE_START_APPLICATION else: if data == self.CA: errorMessage('Transaction aborted by client\n') newState = self.STATE_DONE else: if data == self.CRC16: pass else: if prevState == self.STATE_READY: infoMessage('Retrying\n') retry = (retry + 1) if retry > 3: errorMessage('Too many retry exiting\n') newState = self.STATE_DONE else: newState = self.STATE_READY else: if state == self.STATE_READY: if size <= 0: newState = self.STATE_SEND_EOT else: if retry == 0: packet = [] if loop_counter == 1: packet.extend(struct.unpack(('%uB' % len(filename)), filename)) packet = (packet + [0]) size_string = ('%d ' % file_size) packet.extend(struct.unpack(('%uB' % len(size_string)), size_string)) packet_size = self.PACKET_SIZE else: packet_size = self.PACKET_1K_SIZE packet_string = f.read(packet_size) packet.extend(struct.unpack(('%uB' % len(packet_string)), packet_string)) packet = (packet + ([0] * (packet_size - len(packet)))) if self.sendYModemPacket(packet, packet_number): newState = self.STATE_DONE else: newState = self.STATE_WAITING_ACK else: if state == self.STATE_SEND_EOT: if self.updateAction: self.updateAction((file_size - max(size, 0)), file_size) else: infoMessage(('Sent %05d/%05d\r' % ((file_size - max(size, 0)), file_size))) self.sendByte(self.EOT) newState = self.STATE_WAITING_ACK else: if state == self.STATE_SEND_SESSION_DONE: self.sendYModemPacket(([0] * 128), 0) newState = self.STATE_WAITING_ACK else: if state == self.STATE_START_APPLICATION: self.startApplication() newState = self.STATE_DONE else: if state == self.STATE_DONE: returnValue = False endTime = time.time() infoMessage('\nDone\n') break else: errorMessage(('Unknonw state = %d' % state)) newState = self.STATE_DONE if state != newState: prevState = state state = newState continue else: continue return returnValue except: errorMessage((('File ' + name) + ' open failed\n')) if self.updateAction: self.updateAction(0, 0) return returnValue
def loadFile(self, inputFile=None, startAddress=None, progressReport=None, doErase=True): if inputFile is not None: self.inputFile = inputFile if startAddress is not None: self.startAddress = startAddress returnValue = True f = fileFormatReader(self.inputFile, self.startAddress) try: item0, item1 = f.getRawBinary() self.startAddress = item0 file_content = item1 except IOError: errorMessage((('File ' + self.inputFile) + ' open failed\n')) returnValue = False if returnValue: file_size = len(file_content) packet = [] address = self.startAddress pages = int(((file_size + 1023) / 1024)) startPage = (((self.startAddress & 4294966272L) - 134217728) / 1024) eraseArg = ([(pages - 1)] + range(startPage, (startPage + pages), 1)) infoMessage(('Erasing pages from %d to %d...' % (startPage, ((startPage + pages) - 1)))) if ('STM32W_FLASHER_JLINK_DONT_ERASE' in os.environ or (not doErase)): infoMessage('(skipped)', False) else: reply = self.sendCommand('ERASE', [eraseArg], timeout=10) if reply != [ACK, ACK]: errorMessage(('Unexpected reply %s\n' % repr(reply))) returnValue = False if returnValue: infoMessage('done\n', False) size = 0 while returnValue: packet = [] packet_size = self.packetSize packet_string = file_content[size:(size + packet_size)] packet_size = len(packet_string) if packet_size == 0: infoMessage('\n') break else: size = (size + packet_size) packet.extend(packet_string) if (len(packet) % 2) != 0: packet = (packet + [255]) packet = ([(len(packet) - 1)] + packet) if progressReport: progressReport(size, file_size) else: infoMessage(('Programming %05d/%05d\r' % (size, file_size))) arg1 = u32ToArray(address) arg1.reverse() if (self.serialMode or size == packet_size): reply = self.sendCommand('WRITE', [arg1, packet]) if reply != [ACK, ACK, ACK]: errorMessage(('\n\n+Unexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) returnValue = False else: retries = 0 MAX_RETRIES = 3 while returnValue: reply = self.sendCommand('WRITE_INCREMENTAL', [packet]) if reply != [ACK, ACK]: retries = (retries + 1) if retries > MAX_RETRIES: errorMessage(('\n\nUnexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) returnValue = False break else: errorMessage(('\n\nUnexpected reply %s, packet_size=%d\n' % (repr(reply), packet_size))) infoMessage('Retrying...\n') continue else: break address = (address + packet_size) continue if returnValue: if progressReport == None: infoMessage('Done\n') return returnValue