此文所介绍得《IAP升级文件自动加头部信息》得编译即生成头部信息,只能生成固定信息,但这种方式不能保证升级文件不被恶意篡改,比如,将正常头部加在一份病毒文件头部,则MCU将识别不出来词升级文件是否正常,则跳转后则无法正常运行。因此,我们需要给升级文件加上一些动态得,含有正常文件校验码得信息到头部,使得允许下载进去得升级内容是正常可允许得程序。
我们可以单独开发一个给升级文件加头部得上位机来完成加头部,以及使用拼装方式输出烧录文件或者使用JFLASH工具回读方式生成烧录文件,但均较为繁琐,感谢使用python,轻松开发。
# 指定源文件路径,读出源文件apppath = 'src.bin'with open(apppath,'rb') as appfin: s_app = appfin.read() # 厂商发布者会员账号【8byte】,如"XYZK----"apphead = []s1 = 0apphead.insert(s1,ord('X'))apphead.insert(s1 + 1,ord('Y'))apphead.insert(s1 + 2,ord('Z'))apphead.insert(s1 + 3,ord('K'))for i in range(s1 + 4, 8): apphead.insert(i,ord('-')) # 客户发布者会员账号【8byte】,如"MEIY----"s2 = 8apphead.insert(s2,ord('M'))apphead.insert(s2 + 1,ord('E'))apphead.insert(s2 + 2,ord('I'))apphead.insert(s2 + 3,ord('Y'))for i in range(s2 + 4, 32): apphead.insert(i,ord('-'))####....................#产品类型【8byte】#产品发布者会员账号【8byte】#主控型号【8byte】#硬件版本号【4byte】#软件版本号【4byte】#头部长度【2byte】#实际升级文件长度【4byte】#实际升级文件CRC【4byte】#头部长度【2byte】#预留空间【6byte】#头部CRC【2bytes】# 需要做至少256字节得偏移【对M0来说】for i in range(64, 192): apphead.insert(i,ord('-'))# crc16校验函数def crc16(data): crcGen = 0xE32A # data = bytearray.fromhex(string) crc = 0xFFFF for pos in data: crc ^= pos for i in range(8): if ((crc & 0x01) != 0): crc >>= 1; crc ^= crcGen else: crc >>= 1; return crc
# 指定输出文件路径,可运行脚本手动设置输出文件名或者固定文件名输出,感谢输出固定文件名otapath = 'XXXX.bin'# 输出OTA文件【app头部64字节 + app原文件】with open(otapath,'wb') as fota: fota.write(bytearray(apphead)) fota.write(bytearray(s_app))
至此,已经完成对升级文件得打包工作,接下来,我们将直接生成烧录文件。
需要生成烧录文件,则需要知道,boot程序大小,以及新程序跳转地址,以及片内FLASH加载地址,然后我们使用脚本拼装成一个整体得bin文件,由于我们跳转app前会对OTA数据下载区域进行校验,我们会把头部64字节一并下载到FLASH上。
我们设定:boot大小0x1000, 程序下载地址为0x8000000 + 0x1000, 新程序跳转地址0x8000000 + 0x1000 + 0x100。
接下来对BOOT文件进行读取
bootpath = 'boot.bin'with open(bootpath,'rb') as bootfin: s_boot = bootfin.read() if(os.path.exists(bootpath)): bootlen = os.path.getsize(bootpath) bootend = []if (bootlen <= 4 * 1024): boot_packedlen = 4 * 1024 - bootlen for i in range(0, boot_packedlen): bootend.insert(i, 0xFF)
蕞后进行整体拼装【感谢使用得MCU空间: RAM8K,FLASH64K】
wr_bin_path = 'WR.bin'# 输出烧录文件【boot4K + app文件 + app填充 + boot信息区域 + 数据存储区域 + 整体尾布填充至64K】with open(wr_bin_path,'wb') as fwr: fwr.write(bytearray(s_boot)) fwr.write(bytearray(bootend)) fwr.write(bytearray(apphead)) fwr.write(bytearray(s_app)) fwr.write(bytearray(append)) fwr.write(bytearray(packapp)) fwr.write(bytearray(bootflag)) fwr.write(bytearray(wrbin_end))
接下来,我们可以将WR.bin文件转为WR.hex文件,借助强大得python库完成此项任务:
wr_hex_path = 'WR.hex'from intelhex import compat,bin2hexoffset = 0x8000000sys.exit(bin2hex(wr_bin_path, wr_hex_path, offset))
至此,你将斩获一键生成带头部信息得升级文件+烧录文件得愉快体验!