添加falsh生成

This commit is contained in:
2026-01-01 20:55:25 +08:00
parent 724848a843
commit 3b79dd936d
8 changed files with 971 additions and 5 deletions

View File

@@ -1376,7 +1376,225 @@ class bsp_pwm(QWidget):
if name_widget:
name_widget.setText(saved_config['custom_name'])
# 更新get_bsp_page函数以包含PWM
class bsp_flash(QWidget):
"""Flash BSP配置界面 - 自动识别MCU型号并生成对应的Flash配置"""
def __init__(self, project_path):
super().__init__()
self.project_path = project_path
self.mcu_name = None
self.flash_config = None
# 加载描述
describe_path = os.path.join(CodeGenerator.get_assets_dir("User_code/bsp"), "describe.csv")
self.descriptions = CodeGenerator.load_descriptions(describe_path)
self._detect_mcu()
self._init_ui()
self._load_config()
def _detect_mcu(self):
"""自动检测MCU型号并获取Flash配置"""
ioc_files = [f for f in os.listdir(self.project_path) if f.endswith('.ioc')]
if ioc_files:
ioc_path = os.path.join(self.project_path, ioc_files[0])
self.mcu_name = analyzing_ioc.get_mcu_name_from_ioc(ioc_path)
if self.mcu_name:
self.flash_config = analyzing_ioc.get_flash_config_from_mcu(self.mcu_name)
def _init_ui(self):
layout = QVBoxLayout(self)
# 顶部布局
top_layout = QHBoxLayout()
top_layout.setAlignment(Qt.AlignVCenter)
self.generate_checkbox = CheckBox("生成 Flash 代码")
self.generate_checkbox.stateChanged.connect(self._on_generate_changed)
top_layout.addWidget(self.generate_checkbox, alignment=Qt.AlignLeft)
top_layout.addStretch()
title = SubtitleLabel("Flash 配置 ")
title.setAlignment(Qt.AlignHCenter)
top_layout.addWidget(title, alignment=Qt.AlignHCenter)
top_layout.addStretch()
layout.addLayout(top_layout)
desc = self.descriptions.get("flash", "自动根据MCU型号配置Flash扇区")
if desc:
desc_label = BodyLabel(desc)
desc_label.setWordWrap(True)
layout.addWidget(desc_label)
# 内容区域
self.content_widget = QWidget()
content_layout = QVBoxLayout(self.content_widget)
if not self.flash_config:
no_config_label = BodyLabel("❌ 无法识别MCU型号或不支持的MCU")
content_layout.addWidget(no_config_label)
else:
# 显示检测到的MCU信息
mcu_info = BodyLabel(f"✅ 检测到MCU: {self.mcu_name}")
content_layout.addWidget(mcu_info)
flash_size = (self.flash_config['end_address'] - 0x08000000) // 1024
flash_type = self.flash_config.get('type', 'sector')
if flash_type == 'page':
# F1系列 - Page模式
page_size = self.flash_config.get('page_size', 1)
flash_info = BodyLabel(f"Flash容量: {flash_size} KB ({len(self.flash_config['sectors'])} 个页,每页 {page_size}KB)")
content_layout.addWidget(flash_info)
type_info = BodyLabel(f"📄 Page模式 (F1系列)")
content_layout.addWidget(type_info)
else:
# F4/H7系列 - Sector模式
flash_info = BodyLabel(f"Flash容量: {flash_size} KB ({len(self.flash_config['sectors'])} 个扇区)")
content_layout.addWidget(flash_info)
if self.flash_config['dual_bank']:
max_sector = len(self.flash_config['sectors']) - 1
bank_info = BodyLabel(f"⚠️ 双Bank Flash (Sector 0-{max_sector})")
else:
max_sector = len(self.flash_config['sectors']) - 1
bank_info = BodyLabel(f"单Bank Flash (Sector 0-{max_sector})")
content_layout.addWidget(bank_info)
layout.addWidget(self.content_widget)
self.content_widget.setEnabled(False)
def _on_generate_changed(self, state):
self.content_widget.setEnabled(state == 2)
def is_need_generate(self):
return self.generate_checkbox.isChecked() and self.flash_config is not None
def _generate_bsp_code_internal(self):
if not self.is_need_generate():
return False
if not self.flash_config:
return False
# 生成头文件
if not self._generate_header_file():
return False
# 生成源文件
if not self._generate_source_file():
return False
self._save_config()
return True
def _generate_header_file(self):
"""生成flash.h"""
periph_folder = "flash"
template_base_dir = CodeGenerator.get_assets_dir("User_code/bsp")
template_path = os.path.join(template_base_dir, periph_folder, "flash.h")
if not os.path.exists(template_path):
return False
template_content = CodeGenerator.load_template(template_path)
if not template_content:
return False
# 生成Sector/Page定义
flash_type = self.flash_config.get('type', 'sector')
sector_lines = []
for item in self.flash_config['sectors']:
addr = item['address']
size = item['size']
item_id = item['id']
if flash_type == 'page':
# F1系列 - Page模式
sector_lines.append(
f"#define ADDR_FLASH_PAGE_{item_id} ((uint32_t)0x{addr:08X})"
)
sector_lines.append(
f"/* Base address of Page {item_id}, {size} Kbytes */"
)
else:
# F4/H7系列 - Sector模式
sector_lines.append(
f"#define ADDR_FLASH_SECTOR_{item_id} ((uint32_t)0x{addr:08X})"
)
sector_lines.append(
f"/* Base address of Sector {item_id}, {size} Kbytes */"
)
content = CodeGenerator.replace_auto_generated(
template_content, "AUTO GENERATED FLASH_SECTORS", "\n".join(sector_lines)
)
# 生成结束地址
end_addr = self.flash_config['end_address']
end_line = f"#define ADDR_FLASH_END ((uint32_t)0x{end_addr:08X}) /* End address for flash */"
content = CodeGenerator.replace_auto_generated(
content, "AUTO GENERATED FLASH_END_ADDRESS", end_line
)
output_path = os.path.join(self.project_path, "User/bsp/flash.h")
CodeGenerator.save_with_preserve(output_path, content)
return True
def _generate_source_file(self):
"""生成flash.c"""
periph_folder = "flash"
template_base_dir = CodeGenerator.get_assets_dir("User_code/bsp")
template_path = os.path.join(template_base_dir, periph_folder, "flash.c")
if not os.path.exists(template_path):
return False
template_content = CodeGenerator.load_template(template_path)
if not template_content:
return False
# 生成最大Sector数定义
max_sector = len(self.flash_config['sectors']) - 1
max_sector_line = f"#define BSP_FLASH_MAX_SECTOR {max_sector}"
content = CodeGenerator.replace_auto_generated(
template_content, "AUTO GENERATED FLASH_MAX_SECTOR", max_sector_line
)
# 生成擦除检查代码
erase_check = f" if (sector > 0 && sector <= {max_sector}) {{"
content = CodeGenerator.replace_auto_generated(
content, "AUTO GENERATED FLASH_ERASE_CHECK", erase_check
)
output_path = os.path.join(self.project_path, "User/bsp/flash.c")
CodeGenerator.save_with_preserve(output_path, content)
return True
def _save_config(self):
"""保存配置"""
config_path = os.path.join(self.project_path, "User/bsp/bsp_config.yaml")
config_data = CodeGenerator.load_config(config_path)
config_data['flash'] = {
'enabled': True,
'mcu_name': self.mcu_name,
'dual_bank': self.flash_config['dual_bank'],
'sectors': len(self.flash_config['sectors'])
}
CodeGenerator.save_config(config_data, config_path)
def _load_config(self):
"""加载配置"""
config_path = os.path.join(self.project_path, "User/bsp/bsp_config.yaml")
config_data = CodeGenerator.load_config(config_path)
conf = config_data.get('flash', {})
if conf.get('enabled', False):
self.generate_checkbox.setChecked(True)
# 更新get_bsp_page函数以包含PWM和Flash
def get_bsp_page(peripheral_name, project_path):
"""根据外设名返回对应的页面类没有特殊类则返回默认BspSimplePeripheral"""
name_lower = peripheral_name.lower()
@@ -1387,7 +1605,8 @@ def get_bsp_page(peripheral_name, project_path):
"spi": bsp_spi,
"uart": bsp_uart,
"gpio": bsp_gpio,
"pwm": bsp_pwm, # 添加PWM
"pwm": bsp_pwm,
"flash": bsp_flash, # 添加Flash自动配置
# 以后可以继续添加特殊外设
}
if name_lower in special_classes:

View File

@@ -341,4 +341,242 @@ class analyzing_ioc:
'signal': signal
})
return pwm_channels
return pwm_channels
@staticmethod
def get_mcu_name_from_ioc(ioc_path):
"""
从.ioc文件中获取MCU型号
返回格式: 'STM32F407IGHx'
"""
with open(ioc_path, encoding='utf-8', errors='ignore') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if '=' in line:
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
# 查找MCU名称
if key == 'Mcu.UserName' or key == 'Mcu.Name':
return value
return None
@staticmethod
def get_flash_config_from_mcu(mcu_name):
"""
根据MCU型号返回Flash配置
支持STM32F1/F4/H7系列
返回格式: {
'sectors': [...], # Sector/Page配置列表
'dual_bank': False, # 是否双Bank
'end_address': 0x08100000, # Flash结束地址
'type': 'sector' or 'page' # Flash类型
}
"""
if not mcu_name:
return None
mcu_upper = mcu_name.upper()
# STM32F1系列 - 使用Page而不是Sector
if mcu_upper.startswith('STM32F1'):
return analyzing_ioc._get_stm32f1_flash_config(mcu_upper)
# STM32F4系列 - 使用Sector
elif mcu_upper.startswith('STM32F4'):
return analyzing_ioc._get_stm32f4_flash_config(mcu_upper)
# STM32H7系列 - 使用Sector
elif mcu_upper.startswith('STM32H7'):
return analyzing_ioc._get_stm32h7_flash_config(mcu_upper)
return None
@staticmethod
def _get_stm32f1_flash_config(mcu_upper):
"""
STM32F1系列Flash配置
F1使用Page而不是Sector
- 小/中容量设备: 1KB/page
- 大容量/互联型设备: 2KB/page
容量代码: 4/6=16/32KB, 8/B=64/128KB, C=256KB, D/E=384/512KB, F/G=768KB/1MB
"""
flash_size_map_f1 = {
'4': 16, # 16KB
'6': 32, # 32KB
'8': 64, # 64KB
'B': 128, # 128KB
'C': 256, # 256KB
'D': 384, # 384KB
'E': 512, # 512KB
'F': 768, # 768KB (互联型)
'G': 1024, # 1MB (互联型)
}
# F1命名: STM32F103C8T6, C在索引9
if len(mcu_upper) < 10:
return None
flash_code = mcu_upper[9]
flash_size = flash_size_map_f1.get(flash_code)
if not flash_size:
return None
# 判断页大小: <=128KB用1KB页, >128KB用2KB页
page_size = 1 if flash_size <= 128 else 2
num_pages = flash_size // page_size
config = {
'type': 'page',
'dual_bank': False,
'sectors': [], # F1中这里存的是Page
'page_size': page_size,
}
# 生成所有页
current_address = 0x08000000
for page_id in range(num_pages):
config['sectors'].append({
'id': page_id,
'address': current_address,
'size': page_size
})
current_address += page_size * 1024
config['end_address'] = current_address
return config
@staticmethod
def _get_stm32f4_flash_config(mcu_upper):
"""
STM32F4系列Flash配置
容量代码: C=256KB, E=512KB, G=1MB, I=2MB
"""
flash_size_map = {
'C': 256, # 256KB
'E': 512, # 512KB
'G': 1024, # 1MB
'I': 2048, # 2MB
}
# F4命名: STM32F407IGHx, I在索引9
if len(mcu_upper) < 10:
return None
flash_code = mcu_upper[9]
flash_size = flash_size_map.get(flash_code)
if not flash_size:
return None
config = {
'type': 'sector',
'dual_bank': False,
'sectors': [],
}
# STM32F4系列单Bank Flash布局
# Sector 0-3: 16KB each
# Sector 4: 64KB
# Sector 5-11: 128KB each (如果有)
base_sectors = [
{'id': 0, 'address': 0x08000000, 'size': 16},
{'id': 1, 'address': 0x08004000, 'size': 16},
{'id': 2, 'address': 0x08008000, 'size': 16},
{'id': 3, 'address': 0x0800C000, 'size': 16},
{'id': 4, 'address': 0x08010000, 'size': 64},
]
config['sectors'] = base_sectors.copy()
current_address = 0x08020000
current_id = 5
remaining_kb = flash_size - (16 * 4 + 64) # 减去前5个sector
# 添加128KB的sectors
while remaining_kb > 0 and current_id < 12:
config['sectors'].append({
'id': current_id,
'address': current_address,
'size': 128
})
current_address += 0x20000 # 128KB
remaining_kb -= 128
current_id += 1
# 设置结束地址
config['end_address'] = current_address
# 2MB Flash需要双Bank (Sector 12-23)
if flash_size >= 2048:
config['dual_bank'] = True
# Bank 2 的sectors (12-15: 16KB, 16: 64KB, 17-23: 128KB)
bank2_sectors = [
{'id': 12, 'address': 0x08100000, 'size': 16},
{'id': 13, 'address': 0x08104000, 'size': 16},
{'id': 14, 'address': 0x08108000, 'size': 16},
{'id': 15, 'address': 0x0810C000, 'size': 16},
{'id': 16, 'address': 0x08110000, 'size': 64},
{'id': 17, 'address': 0x08120000, 'size': 128},
{'id': 18, 'address': 0x08140000, 'size': 128},
{'id': 19, 'address': 0x08160000, 'size': 128},
{'id': 20, 'address': 0x08180000, 'size': 128},
{'id': 21, 'address': 0x081A0000, 'size': 128},
{'id': 22, 'address': 0x081C0000, 'size': 128},
{'id': 23, 'address': 0x081E0000, 'size': 128},
]
config['sectors'].extend(bank2_sectors)
config['end_address'] = 0x08200000
return config
@staticmethod
def _get_stm32h7_flash_config(mcu_upper):
"""
STM32H7系列Flash配置
- 每个Sector 128KB
- 单Bank: 8个Sector (1MB)
- 双Bank: 16个Sector (2MB), 每个Bank 8个Sector
容量代码: B=128KB, G=1MB, I=2MB
命名格式: STM32H7 + 23 + V(引脚) + G(容量) + T(封装) + 6
"""
flash_size_map_h7 = {
'B': 128, # 128KB (1个Sector)
'G': 1024, # 1MB (8个Sector, 单Bank)
'I': 2048, # 2MB (16个Sector, 双Bank)
}
# H7命名: STM32H723VGT6, G在索引10
if len(mcu_upper) < 11:
return None
flash_code = mcu_upper[10]
flash_size = flash_size_map_h7.get(flash_code)
if not flash_size:
return None
config = {
'type': 'sector',
'dual_bank': flash_size >= 2048,
'sectors': [],
}
num_sectors = flash_size // 128 # 每个Sector 128KB
# 生成Sector配置
current_address = 0x08000000
for sector_id in range(num_sectors):
config['sectors'].append({
'id': sector_id,
'address': current_address,
'size': 128,
'bank': 1 if sector_id < 8 else 2 # Bank信息
})
current_address += 0x20000 # 128KB
config['end_address'] = current_address
return config