积累更新
This commit is contained in:
2
source/device/function/__init__.py
Normal file
2
source/device/function/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from . import frame
|
||||
from . import file_upgrade
|
||||
@@ -1,10 +1,6 @@
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from crc import Calculator, Crc16
|
||||
|
||||
from tools.IntelHex import file_IntelHex_to_Bin, file_Bin_to_IntelHex
|
||||
|
||||
|
||||
Header_Tag = {
|
||||
'file_type': [0x00, 2], # 0 - 文件类型; 2byte
|
||||
@@ -183,19 +179,6 @@ def parser_version_info(file_bin: bytearray, base_addr:int):
|
||||
|
||||
return block_version
|
||||
|
||||
def test1(fp: Path):
|
||||
""" bin文件生成测试 """
|
||||
file1 = Path(fp)
|
||||
path1 = file1.parent / (file1.stem + ".bin")
|
||||
data1 = file1.read_text()
|
||||
data2 = file_IntelHex_to_Bin(data1, 0x3F0100)
|
||||
path1.write_bytes(data2)
|
||||
|
||||
# 测试Bin到IntelHex
|
||||
bin = Path(fp).read_bytes()
|
||||
result = file_Bin_to_IntelHex(bin, 0x80000, memory_width=2)
|
||||
(fp.parent / (fp.stem + ".hex")).write_text(result)
|
||||
|
||||
|
||||
def test2():
|
||||
""" 校验, 加密测试 """
|
||||
@@ -237,6 +220,6 @@ def task5():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# path_bin = Path("F:\\Work\\FPGA\\Test\\Vivado\\test_update\\test_update.vitis\\upgrade_system\\Debug\\sd_card\\BOOT.BIN")
|
||||
# GeneratePackage_Demo_Xilinx(path_bin)
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
pass
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import struct
|
||||
from crc import Calculator, Crc16
|
||||
from tools.ByteConv import trans_list_to_str, trans_str_to_list, display_hex
|
||||
|
||||
from .. import tools
|
||||
|
||||
modbus_map = {
|
||||
# 1 - Hex
|
||||
@@ -332,14 +333,14 @@ def display_data(address: int, data: bytes, modbus_map: dict=modbus_map) -> dict
|
||||
data_label, data_len = "未知数据", 1
|
||||
if idx not in modbus_map.keys():
|
||||
item = convert_regs_to_int(data, 1, signed=False)
|
||||
item = display_hex(item, 4)
|
||||
item = tools.ByteConv.display_hex(item, 4)
|
||||
else:
|
||||
current_map = modbus_map[idx]
|
||||
data_label = current_map[0]
|
||||
if current_map[1] == 1:
|
||||
""" Hex字符表示 """
|
||||
item = convert_regs_to_int(data, 1, signed=False)
|
||||
item = display_hex(item, 4)
|
||||
item = tools.ByteConv.display_hex(item, 4)
|
||||
elif current_map[1] == 2:
|
||||
""" 16位数值表示 """
|
||||
item = convert_regs_to_int(data, 1)
|
||||
@@ -359,12 +360,12 @@ def display_data(address: int, data: bytes, modbus_map: dict=modbus_map) -> dict
|
||||
item = item.decode()
|
||||
except Exception as ex:
|
||||
item_len = sum([any(item[i:]) for i in range(len(item))])
|
||||
item = trans_list_to_str(item[:item_len])
|
||||
item = tools.ByteConv.trans_list_to_str(item[:item_len])
|
||||
elif current_map[1] == 5:
|
||||
""" 载波地址表示 """
|
||||
data_len = current_map[2]
|
||||
item = swapping_words(data, data_len)
|
||||
item = trans_list_to_str(item)
|
||||
item = tools.ByteConv.trans_list_to_str(item)
|
||||
elif current_map[1] == 6:
|
||||
""" 浮点数值表示 """
|
||||
data_len = 2
|
||||
@@ -388,7 +389,7 @@ def print_display(output_data: dict):
|
||||
for key, value in output_data.items():
|
||||
label = value[0]
|
||||
data = "-".join(map(str, value[1])) if type(value) == list else value[1]
|
||||
print(f"{display_hex(key, 4)}: {data:<{data_len_max}} {label:<{label_len_max}}")
|
||||
print(f"{tools.ByteConv.display_hex(key, 4)}: {data:<{data_len_max}} {label:<{label_len_max}}")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
def trans_list_to_str(data: list) -> str:
|
||||
""" 标准串口字符串表示 """
|
||||
func_trans = lambda x: ('00' + hex(x % 256)[2:])[-2:].upper()
|
||||
return " ".join(map(func_trans, data))
|
||||
|
||||
|
||||
def trans_str_to_list(data: str) -> list:
|
||||
""" 标准串口字符串转换列表 """
|
||||
func_trans = lambda x: int(x, 16)
|
||||
return list(map(func_trans, data.strip().split(" ")))
|
||||
|
||||
|
||||
def conv_int_to_array(num: int, big_end=False):
|
||||
""" 数值转字节数组 """
|
||||
result = [0, 0, 0, 0]
|
||||
if big_end:
|
||||
indexlist = reversed(range(len(result)))
|
||||
else:
|
||||
indexlist = range(len(result))
|
||||
|
||||
for i in indexlist:
|
||||
result[i] = int(num % 0x100)
|
||||
num //= 0x100
|
||||
return result
|
||||
|
||||
|
||||
def display_hex(data:int, length:int=2) -> str:
|
||||
""" Hex字符固定最小长度表示 """
|
||||
return f"0x{data:0{length}X}"
|
||||
@@ -1,142 +0,0 @@
|
||||
def calculate_checksum(data):
|
||||
""" 计算校验域 """
|
||||
checksum = 0
|
||||
for i in range(0, len(data), 2):
|
||||
checksum += int(data[i: i+2], 16)
|
||||
return (0x100 - checksum) & 0xFF
|
||||
|
||||
|
||||
def file_IntelHex_to_Bin(file_data, base_address=0, len_max=1, **kwargs):
|
||||
"""
|
||||
将Intel Hex格式文件转换为Bin格式;
|
||||
"""
|
||||
if base_address == 0:
|
||||
if file_data[8] == '2':
|
||||
base_address = int(file_data[9: 13], 16) * 0x100
|
||||
offset_begin = 16
|
||||
elif file_data[8] == '4':
|
||||
base_address = int(file_data[9: 13], 16) * 0x10000
|
||||
offset_begin = 16
|
||||
else:
|
||||
base_address = 0
|
||||
offset_begin = 0
|
||||
base_address += int(file_data[offset_begin + 3: offset_begin + 7], 16)
|
||||
base_address &= ~0x0FFF
|
||||
|
||||
len_space = len_max
|
||||
result = bytearray(len_space).replace(b'\x00', b'\xff')
|
||||
lines = file_data.split('\n')
|
||||
offset = 0
|
||||
max_address = 0
|
||||
for line in lines:
|
||||
if line[0] == ':':
|
||||
checksum = sum([int(x, 16) * (15 * (~i & 0x01) + 1) for i, x in enumerate(line[1:])])
|
||||
if (checksum & 0x00FF) != 0:
|
||||
raise Exception('Hex file checksum error!')
|
||||
|
||||
if line[7:9] == '00':
|
||||
len_line = int(line[1:3], 16)
|
||||
address = offset + int(line[3:7], 16) - base_address
|
||||
data = bytearray.fromhex(line[9:-2])
|
||||
if 'conv_end' in kwargs.keys():
|
||||
address *= 2
|
||||
if kwargs['conv_end']:
|
||||
for i in range(0, len_line, 2):
|
||||
t = data[i]
|
||||
data[i] = data[i+1]
|
||||
data[i+1] = t
|
||||
|
||||
if (address + len_line) > max_address:
|
||||
max_address = address + len_line
|
||||
if max_address >= len_space:
|
||||
if len_max == 1:
|
||||
result += bytearray(max_address - len_space).replace(b'\x00', b'\xff')
|
||||
len_space += max_address - len_space
|
||||
else:
|
||||
raise Exception("Bin file Oversize.")
|
||||
result[address:address+len_line] = data
|
||||
|
||||
elif line[7:9] == '01':
|
||||
break
|
||||
elif line[7:9] == '02':
|
||||
offset = int(line[9:-2], 16) * 16
|
||||
elif line[7:9] == '03':
|
||||
pass
|
||||
elif line[7:9] == '04': # 拓展地址偏移
|
||||
offset = int(line[9:-2], 16) * 2**16
|
||||
elif line[7:9] == '05':
|
||||
pass
|
||||
return result[:max_address]
|
||||
|
||||
|
||||
def file_Bin_to_IntelHex(file_data: bytearray, base_address=0, **kwargs):
|
||||
"""
|
||||
将Bin格式文件转换为Intel Hex格式;
|
||||
"""
|
||||
chunk_size = 32
|
||||
rom_width = 8
|
||||
memory_width = 8
|
||||
if 'chunk_size' in kwargs.keys():
|
||||
""" 数据分块大小 """
|
||||
chunk_size = kwargs['chunk_size']
|
||||
if 'memory_width' in kwargs.keys():
|
||||
""" 地址数据位宽 """
|
||||
memory_width = kwargs['memory_width'] * 8
|
||||
if 'rom_width' in kwargs.keys():
|
||||
""" rom数据位宽 """
|
||||
rom_width = kwargs['rom_width'] * 8
|
||||
|
||||
def record_extern_address(address, record_type):
|
||||
""" 添加地址记录 """
|
||||
if record_type == 4:
|
||||
record_data = (address & 0xFFFF0000) >> 16
|
||||
elif record_type == 2:
|
||||
record_data = (address & 0xFFFF0) >> 4
|
||||
else:
|
||||
raise Exception("Unknow record tye.")
|
||||
|
||||
hex_record = f':020000{record_type:02X}{record_data:04X}'
|
||||
hex_record += f'{calculate_checksum(hex_record[1:]):02X}\n'
|
||||
return hex_record
|
||||
|
||||
result = str()
|
||||
|
||||
# 添加开始记录
|
||||
extern_address = 0
|
||||
if base_address >= 2 ** 32:
|
||||
""" 超过最大可表示范围, 抛出异常 """
|
||||
raise Exception("base_address oversize")
|
||||
elif base_address >= 2 ** 16:
|
||||
result += record_extern_address(base_address, 4)
|
||||
extern_address = base_address & 0xFFFF0000
|
||||
elif base_address >= 2 ** 4:
|
||||
result += record_extern_address(base_address, 2)
|
||||
extern_address = base_address & 0xFFFF0
|
||||
|
||||
record_type = 0
|
||||
binary_offset = 0
|
||||
while binary_offset < len(file_data):
|
||||
""" 循环分块处理数据 """
|
||||
data_chunk = file_data[binary_offset: binary_offset + chunk_size]
|
||||
|
||||
record_len = len(data_chunk)
|
||||
record_data = data_chunk
|
||||
record_addr = (base_address - extern_address + (binary_offset // (memory_width // 8)))
|
||||
if record_addr >= 0x10000:
|
||||
result += record_extern_address((base_address + (binary_offset // (memory_width // 8))), 4)
|
||||
extern_address = (base_address + (binary_offset // (memory_width // 8))) & 0xFFFF0000
|
||||
continue
|
||||
|
||||
# 构造记录
|
||||
hex_record = f':{record_len:02X}{record_addr:04X}{record_type:02X}'
|
||||
hex_record += ''.join(f'{byte:02X}' for byte in record_data)
|
||||
hex_record += f'{calculate_checksum(hex_record[1:]):02X}\n'
|
||||
result += hex_record
|
||||
|
||||
binary_offset += chunk_size
|
||||
|
||||
# 添加结束记录
|
||||
hex_record = f':00000001FF\n'
|
||||
result += hex_record
|
||||
|
||||
return result
|
||||
Reference in New Issue
Block a user