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 flashImage (interface, inputFile, startAddress, doErase=True): def progressReport(size, fileSize): infoMessage ("Programming %05d/%05d\r"%(size,fileSize)) infoMessage ("Programming user flash\n") if not interface.programUserFlash(inputFile, startAddress, progressReport, doErase): infoMessage("Failed \n") else: infoMessage("Done \n")
def verifyFlashImage(interface, inputFile, startAddress): def progressReport(size, fileSize): infoMessage("Verifying %05d/%05d\r" % (size, fileSize)) infoMessage("Verifying user flash\n") if not interface.verifyFlash(inputFile, startAddress, progressReport): infoMessage("Failed \n") else: infoMessage("Done \n")
def resetDevice(interface): infoMessage("Resetting device\n") returnValue = not interface.startApplication(0) if (returnValue): infoMessage("Failed \n") else: infoMessage("Done \n")
def resetDevice(interface): infoMessage("Resetting device\n") returnValue = not interface.startApplication(0) if returnValue: infoMessage("Failed \n") else: infoMessage("Done \n")
def flashImage(interface, inputFile, startAddress, doErase=True): def progressReport(size, fileSize): infoMessage("Programming %05d/%05d\r" % (size, fileSize)) infoMessage("Programming user flash\n") if not interface.programUserFlash(inputFile, startAddress, progressReport, doErase): infoMessage("Failed \n") else: infoMessage("Done \n")
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 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 printBanner(): infoMessage("STM32W flasher utility version %s\n" % version)
def eraseUserFlash(interface): infoMessage("Erasing user flash (mass erase)\n") if not interface.eraseUserFlash(): infoMessage("Failed \n") else: infoMessage("Done \n")
def startApplication(interface, startAddress): infoMessage("Starting application from address: %08x\n" % startAddress) if not interface.startApplication(startAddress): infoMessage("Failed \n") else: infoMessage("Done \n")
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
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") sys.exit(-1)
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 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, 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 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 sendCommand(self, command, args=[], timeout=2, traceCommands=False): def timedRead(port, timeout, serialMode, bytes=1): reply = [] r = '' for byte in range(bytes): startTime = time.time() r1 = '' while (time.time() - startTime) < timeout: r1 = port.read(1) if len(r1) > 0: r = (r + r1) startTime = time.time() break else: if serialMode: continue else: time.sleep(0.001) continue if len(r1) == 0: break else: continue if len(r) > 0: reply.extend(struct.unpack(('B' * len(r)), r)) return reply reply = [] error = False if command in commands: item0, item1 = (commands[command]) commandID = item0 replyLength = item1 if command == 'READ': replyLength = (((args[1])[0]) + 4) else: error = True if error: pass else: if traceCommands: infoMessage(('Sending command: %02x %02x\n' % (commandID, (255 - commandID)))) self.serialPort.write(struct.pack('BB', commandID, (255 - commandID))) r = timedRead(self.serialPort, timeout, self.serialMode, 1) reply = (reply + r) if (len(r) != 1 or (r[0]) != ACK): error = True if error: pass else: for arg in args: arg = (arg + [self.checksum(arg)]) if traceCommands: infoMessage((('Sending arg:' + ','.join(('%02x' % a) for a in arg)) + '\n')) self.serialPort.write(struct.pack(('B' * len(arg)), *arg)) r = timedRead(self.serialPort, timeout, self.serialMode, 1) reply = (reply + r) if (len(r) != 1 or (r[0]) != ACK): error = True break else: continue if ((not error) and len(reply) < replyLength): reply = (reply + timedRead(self.serialPort, timeout, self.serialMode, (replyLength - len(reply)))) if (command == 'GET' and len(reply) == replyLength): reply = (reply + timedRead(self.serialPort, timeout, self.serialMode, ((reply[1]) + 2))) if traceCommands: infoMessage(('Reply was %s\n' % hexString(reply))) return reply
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
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") sys.exit(-1)
def progressReport(size, fileSize): infoMessage("Programming %05d/%05d\r" % (size, fileSize))
def sendCommand(self, command, args=[], timeout=2, traceCommands=False): def timedRead(port, timeout, serialMode, bytes=1): reply = [] r = '' for byte in range(bytes): startTime = time.time() r1 = '' while (time.time() - startTime) < timeout: r1 = port.read(1) if len(r1) > 0: r = (r + r1) startTime = time.time() break else: if serialMode: continue else: time.sleep(0.001) continue if len(r1) == 0: break else: continue if len(r) > 0: reply.extend(struct.unpack(('B' * len(r)), r)) return reply reply = [] error = False if command in commands: item0, item1 = (commands[command]) commandID = item0 replyLength = item1 if command == 'READ': replyLength = (((args[1])[0]) + 4) else: error = True if error: pass else: if traceCommands: infoMessage( ('Sending command: %02x %02x\n' % (commandID, (255 - commandID)))) self.serialPort.write( struct.pack('BB', commandID, (255 - commandID))) r = timedRead(self.serialPort, timeout, self.serialMode, 1) reply = (reply + r) if (len(r) != 1 or (r[0]) != ACK): error = True if error: pass else: for arg in args: arg = (arg + [self.checksum(arg)]) if traceCommands: infoMessage((('Sending arg:' + ','.join( ('%02x' % a) for a in arg)) + '\n')) self.serialPort.write(struct.pack(('B' * len(arg)), *arg)) r = timedRead(self.serialPort, timeout, self.serialMode, 1) reply = (reply + r) if (len(r) != 1 or (r[0]) != ACK): error = True break else: continue if ((not error) and len(reply) < replyLength): reply = (reply + timedRead(self.serialPort, timeout, self.serialMode, (replyLength - len(reply)))) if (command == 'GET' and len(reply) == replyLength): reply = (reply + timedRead(self.serialPort, timeout, self.serialMode, ((reply[1]) + 2))) if traceCommands: infoMessage(('Reply was %s\n' % hexString(reply))) return reply
def progressReport(size, fileSize): infoMessage("Verifying %05d/%05d\r" % (size, fileSize))
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 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