|------------|---|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------|
| generate_autosar_framework.py: app,bsw,rte file |||||
| serial num | sheet || function | note |
| 1 | || 1.判断输入的参数必须是脚本+表格 2.在当前路径下面,生成output文件夹,output下面再分别创建app,bsw,rte三个子文件夹。 3.如果当前bsw/osif存在将当前路径下存在这几个文件,就将删除掉里面的文件,再拷贝utilities下面的文件拷贝到bsw/osif下面,如果没有,就直接从utilities下面的文件拷贝到bsw/osif 4.在bsw/osif/下面,如果没有osif_task_cfg.c和osif_task_cfg.h,则创建这两个文件,如果有则删除再创建 | |
| 2 | || 1.计算整个表格文件的md5值,其中iter(lambda: f.read(4096), b""), 表示每次读4k的数据,直到读到的数据b"",就不会在读取了 """计算文件的MD5哈希值""" hash_md5 = hashlib.md5() with open(filepath, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() | |
| 3 | History || 1.读取History sheet页中的数据,将行和列数据,以及计算的md5的值数据信息合成history_lines作为各个文件的base_comment base_comment = "/*\n" + "\n".join(history_lines) + "\n */\n\n" | |
| 4 | Task || 根据Task 页生成osif_task_cfg.h 文件: struct_part = """#ifndef OSIF_TASK_CONFIG_H #define OSIF_TASK_CONFIG_H #include "osif.h" typedef void (*EventFuncPtr)(void); typedef struct { \tchar * name; \tosTask_t taskHandler; \tuint16_t StackSize; \tuint8_t prior; \tEventFuncPtr EventMapTable32; \tuint8_t taskRunFlag; \tuint8_t slpComfirmFlag; \tuint8_t HostReqSlpFlag; \tuint32_t RunTick; \tuint32_t softWdtTimeout; \tStaticTask_t *TCBBuffer; \tStackType_t *StackBuffer; } TaskParams_ST; """ 1.打开读取xlsx表格中的Task sheet页中的数据,脚本输出读取到Task 数据行和列 2.定义task_names_series,valid_tasks_enum,raw_task_names, orig_task_names,wdt_timeout_values列表,task_names_series = df.iloc2:,0 ,从Task sheet页中的df.iloc2:,0 截取切片,表示从第二行第一列开始,读取所有行第一列的数据。 | |
| 5 | Task || 3.遍历整个task_names_series列表,处理整个Task 页数据。 for val in task_names_series: if pd.isna(val): continue name_orig = str(val).strip() if name_orig == '': continue orig_task_names.append(name_orig) clean = sanitize_enum_name(name_orig) raw_task_names.append(clean) valid_tasks_enum.append("TASK_ID_" + clean.upper()) 4.读取看门狗的时间,读取第4列第三行开始 for i, task in enumerate(raw_task_names): row_idx = 2 + i wdt_cell = df.ilocrow_idx, 3 try: wdt_val = int(float(wdt_cell)) if pd.notna(wdt_cell) else 0 except: wdt_val = 0 print(f"警告:任务 {orig_task_namesi} 看门狗超时不是有效数字,使用0") wdt_timeout_values.append(wdt_val) 5. 创建任务枚举 enum_lines = "typedef enum", "{" for item in valid_tasks_enum: enum_lines.append(f"\t{item},") enum_lines.append("\tTASK_ID_MAX") enum_lines.append("} TaskID_E;") enum_part = "\n".join(enum_lines) extern_decl = "extern TaskParams_ST stTaskCfgTblTASK_ID_MAX;\n\n" | |
| 6 | Task || 6.读取common事件:第2行第6列开始 common_row = df.iloc1,5: common_suffixes = \[\] for cell in common_row: if pd.isna(cell): continue suffix = str(cell).strip() if suffix == '': continue clean_suffix = sanitize_enum_name(suffix).upper() common_suffixes.append(clean_suffix) 生成公共事件枚举 common_evt_lines = "/\*\*\*\*\*\*\*\*\*\*\* COMMON EVENT \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/" common_evt_lines.append("typedef enum") common_evt_lines.append("{") if common_suffixes: for i, suffix in enumerate(common_suffixes): line = f"\tEVT_COMMON_{suffix}" if i < len(common_suffixes) - 1: line += "," common_evt_lines.append(line) else: common_evt_lines.append("\t/* No common events defined */") common_evt_lines.append("} CommonEvt_E;") common_evt_enum = "\n".join(common_evt_lines) + "\n\n" | |
| 7 | Task || def capitalize_first(s): """将字符串首字母大写,其余保持不变""" if not s: return s return s0.upper() + s1: 7.为每个任务生成事件枚举(私有事件从第2行第5列读取),遍历所有的任务,定义私有事件,pd.notna 非缺失值 task_events_list = \[\] task_private_events = \[\] for i, task in enumerate(raw_task_names): task_upper = task.upper() task_camel = capitalize_first(task) private_cell = df.ilocrow_idx, 4 private_names = \[\] if pd.notna(private_cell): cell_str = str(private_cell).strip() if cell_str: lines = line.strip() for line in cell_str.splitlines() if line.strip() for line in lines: clean_name = sanitize_enum_name(line).upper() private_names.append(clean_name) task_private_events.append(private_names) total_events = len(common_suffixes) + len(private_names) if total_events > 32: handle_error_and_exit( f"错误:任务 {task_upper} 的事件总数(公有 {len(common_suffixes)} + 私有 {len(private_names)} = {total_events})超过 32 个,生成终止。") items = \[\] for suffix in common_suffixes: items.append(f"EVT_{task_upper}{suffix}") for name in private_names: items.append(f"EVT{task_upper}{name}") if not items: print(f"警告:任务 {task_upper} 没有定义任何事件,跳过生成") continue lines = \[\] lines.append(f"/*********** {task_upper} EVENT ****************************/") lines.append("typedef enum") lines.append("{") for j in range(len(common_suffixes)): enum_name = itemsj if j < len(items) - 1: lines.append(f"\t{enum_name},") else: lines.append(f"\t{enum_name}") if private_names: lines.append("\t/***** Private Event ******/") for j in range(len(common_suffixes), len(items)): enum_name = itemsj if j < len(items) - 1: lines.append(f"\t{enum_name},") else: lines.append(f"\t{enum_name}") lines.append(f"}} {task_camel}Evt_E;\n") task_events_list.append("\n".join(lines)) task_events_str = "\n".join(task_events_list) | |
| 8 | Task || 8.生成函数声明 func_decl_list = \[\] func_decl_list.append("\n/* Task Register Function Declarations */") for i, task in enumerate(raw_task_names): task_camel = capitalize_first(task) func_decl = f"void OSIF{task_camel}RegisterRunnable({task_camel}Evt_E event, EventFuncPtr func);" func_decl_list.append(func_decl) func_decl_str = "\n".join(func_decl_list) header_content = (struct_part + "\n" + enum_part + "\n\n" + extern_decl + common_evt_enum + task_events_str + func_decl_str + "\n\n#endif /* OSIF_TASK_CONFIG_H */") header_path = os.path.join(sub_dir_path, header_file) header_content = add_file_trailer(header_content, header_path) if os.path.exists(header_path): os.chmod(header_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(header_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(header_content) print(f"成功将头文件写入 '{header_path}'。") set_readonly(header_path) except Exception as e: handle_error_and_exit(f"写入文件时发生错误:{e}") | |
| 9 | Task || 9.生成osif_task_cfg.c: //获取每个任务的优先级 task_data = \[\] for i, task_orig in enumerate(orig_task_names): row_idx = 2 + i prio_cell = df.ilocrow_idx, 1 try: priority = int(float(prio_cell)) if pd.notna(prio_cell) else 0 except: priority = 0 print(f"警告:任务 {task_orig} 优先级不是有效数字,使用0") stack_cell = df.ilocrow_idx, 2 try: stack = int(float(stack_cell)) if pd.notna(stack_cell) else 0 except: stack = 0 print(f"警告:任务 {task_orig} 栈大小不是有效数字,使用0") task_data.append((task_orig, stack, priority)) fields_per_task = \[\] static_buffer_lines = \[\] cfg_lines = '#include "osif_task_cfg.h"', '' cfg_lines.append('/* Compiler Detection */') cfg_lines.append('/* 默认不使用自定义段,如需启用请手动定义 USE_TASK_STACK_SECTION 宏 */') cfg_lines.append('#if defined(USE_TASK_STACK_SECTION)') cfg_lines.append(' #if defined(CC_ARM) || defined(ARMCLANG_VERSION)') cfg_lines.append(' /* Keil MDK-ARM / ARM Compiler */') cfg_lines.append(' #define TASK_STACK_ATTR attribute((section(".task_stack")))') cfg_lines.append(' #define TASK_ALIGN_ATTR attribute((aligned(32)))') cfg_lines.append(' #elif defined(TI_COMPILER)') cfg_lines.append(' /* TI Compiler */') cfg_lines.append(' #define TASK_STACK_ATTR') cfg_lines.append(' #define TASK_ALIGN_ATTR') cfg_lines.append(' #elif defined(ICCARM)') cfg_lines.append(' /* IAR Compiler */') cfg_lines.append(' #define TASK_STACK_ATTR attribute((section(".task_stack")))') cfg_lines.append(' #define TASK_ALIGN_ATTR attribute((aligned(32)))') cfg_lines.append(' #elif defined(GNUC)') cfg_lines.append(' /* ARM GCC / GNU Compiler */') cfg_lines.append(' #define TASK_STACK_ATTR attribute((section(".task_stack")))') cfg_lines.append(' #define TASK_ALIGN_ATTR attribute((aligned(32)))') cfg_lines.append(' #else') cfg_lines.append(' #define TASK_STACK_ATTR') cfg_lines.append(' #define TASK_ALIGN_ATTR') cfg_lines.append(' #endif') cfg_lines.append('#endif') cfg_lines.append('') cfg_lines.append('/* Static Task Buffers */') | |
| 10 | Task || def add_file_trailer(content, filepath): """根据文件类型在内容末尾添加尾部(空行或结束注释)""" ext = os.path.splitext(filepath)1 if ext == '.c': return content + "\n/* End of file */\n" elif ext in '.h', '.txt': return content + "\n" else: return content //定义tcb for i, (task_orig, stack, priority) in enumerate(task_data): task_lower = raw_task_namesi task_upper = task_lower.upper() stack_words = stack // 4 # 转换为字(4字节)单位 # 生成静态缓冲区定义 cfg_lines.append(f'#if defined(TASK_STACK_ATTR) && defined(TASK_ALIGN_ATTR)') cfg_lines.append(f'TASK_ALIGN_ATTR static StackType_t {task_lower}task_stack{stack_words} TASK_STACK_ATTR;') cfg_lines.append('#else') cfg_lines.append(f'static StackType_t {task_lower}task_stack{stack_words};') cfg_lines.append('#endif') cfg_lines.append(f'static StaticTask_t {task_lower}task_tcb;') if i < len(task_data) - 1: cfg_lines.append('') # 获取 WDT 超时值 wdt_timeout = wdt_timeout_valuesi fields = f'"{task_orig}"', # name 'NULL', # taskHandler str(stack), # StackSize str(priority), # prior '{0}', # EventMapTable\[32 '0', # taskRunFlag '0', # slpComfirmFlag '0', # HostReqSlpFlag '0', # RunTick str(wdt_timeout) # softWdtTimeout ] # TCBBuffer和StackBuffer在后面单独添加,因为它们需要指针 fields_per_task.append((task_lower, fields)) | |
| 11 | Task || //任务参数列表 cfg_lines.append('') cfg_lines.append('TaskParams_ST stTaskCfgTblTASK_ID_MAX =') cfg_lines.append('{') #按照数据大小格式,填充任务参数列表 max_widths = 0 * 12 # 12个字段(10个基础字段 + 2个指针字段) for task_lower, fields in fields_per_task: task_tcb_ptr = f'&{task_lower}task_tcb' task_stack_ptr = f'{task_lower}task_stack' all_fields = fields + task_tcb_ptr, task_stack_ptr for i, f in enumerate(all_fields): max_widthsi = max(max_widthsi, len(f)) for idx, (task_lower, fields) in enumerate(fields_per_task): task_tcb_ptr = f'&{task_lower}task_tcb' task_stack_ptr = f'{task_lower}task_stack' all_fields = fields + task_tcb_ptr, task_stack_ptr formatted = f.ljust(max_widths\[i) for i, f in enumerate(all_fields)] line = '\t{ ' + ', '.join(formatted) + ' }' if idx < len(fields_per_task) - 1: line += ',' cfg_lines.append(line) cfg_lines.append('};') | |
| 12 | Task || def add_file_trailer(content, filepath): """根据文件类型在内容末尾添加尾部(空行或结束注释)""" ext = os.path.splitext(filepath)1 if ext == '.c': return content + "\n/* End of file */\n" elif ext in '.h', '.txt': return content + "\n" else: return content //所有任务订阅函数 cfg_lines.append('') cfg_lines.append('/* Task Register Functions */') for i, task in enumerate(raw_task_names): task_camel = capitalize_first(task) task_upper = task.upper() func_def = f"""void OSIF{task_camel}RegisterRunnable({task_camel}Evt_E event, EventFuncPtr func) {{ stTaskCfgTblTASK_ID_{task_upper}.EventMapTableevent = func; }}""" cfg_lines.append(func_def) if i < len(raw_task_names) - 1: cfg_lines.append('') cfg_content = '\n'.join(cfg_lines) cfg_path = os.path.join(sub_dir_path, cfg_file) cfg_content = add_file_trailer(cfg_content, cfg_path) if os.path.exists(cfg_path): os.chmod(cfg_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(cfg_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(cfg_content) print(f"成功将配置文件写入 '{cfg_path}'。") set_readonly(cfg_path) except Exception as e: handle_error_and_exit(f"写入文件时发生错误:{e}") | |
| 13 | 发布履历.Txt || 10. 生成 发布履历.Txt history_filename = "发布履历.txt" history_path = os.path.join(sub_dir_path, history_filename) pure_lines = \[\] for line in base_comment.splitlines(): if line.startswith("/*") or line.startswith(" */"): continue if line.startswith(" * "): pure_lines.append(line3:) elif line.startswith(" *"): pure_lines.append(line2:) pure_lines.append(line) pure_content = "\n".join(pure_lines) pure_content = add_file_trailer(pure_content, history_path) if os.path.exists(history_path): os.chmod(history_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(history_path, 'w', encoding='utf-8-sig') as f: f.write(pure_content) print(f"成功将发布履历写入 '{history_path}'。") set_readonly(history_path) except Exception as e: handle_error_and_exit(f"写入文件时发生错误:{e}") | |
| 14 | 拷贝文件到bsw下 || 11. 拷贝文件到bsw下 script_dir = os.path.dirname(os.path.abspath(file)) src_util_dir = os.path.join(script_dir, "util", "OSIF") copy_util_files(src_util_dir, sub_dir_path, readonly_comment) bsw_dir = os.path.join(base_dir, "bsw") try: os.makedirs(bsw_dir, exist_ok=True) print(f"创建目录 '{bsw_dir}' 成功。") except Exception as e: handle_error_and_exit(f"创建目录 '{bsw_dir}' 时发生错误:{e}") dst_osif = os.path.join(bsw_dir, sub_dir) try: shutil.move(sub_dir_path, dst_osif) print(f"移动目录 '{sub_dir_path}' -> '{dst_osif}' 成功。") sub_dir_path = dst_osif except Exception as e: handle_error_and_exit(f"移动目录 '{sub_dir_path}' 时发生错误:{e}") | |
| 15 | CS Port Interfaces || 1.读取CS Port Interfaces 工作表 interface_functions = {} try: df_cs = pd.read_excel(filename, sheet_name="CS Port Interfaces", header=None) df_cs0 = df_cs0.ffill() print(f"成功读取 'CS Port Interfaces' 工作表,共 {df_cs.shape0} 行,{df_cs.shape1} 列。") for idx, row in df_cs.iloc1:.iterrows(): task_orig = str(row0).strip() if pd.notna(row0) else "" decl = str(row1).strip() if pd.notna(row1) else "" desc = str(row2).strip() if pd.notna(row2) else "" if not task_orig or not decl: continue task_clean = sanitize_enum_name(task_orig) if task_clean not in raw_task_names: handle_error_and_exit( f"错误:CS Port Interfaces 中的任务名 '{task_orig}' 未在 Task 工作表中定义,生成终止。") if task_clean not in interface_functions: interface_functionstask_clean = \[\] interface_functionstask_clean.append((decl, desc)) print(f"共收集到接口函数: {sum(len(v) for v in interface_functions.values())} 个") except Exception as e: handle_error_and_exit(f"错误:读取 'CS Port Interfaces' 工作表时出错:{e}") | |
| 16 | SR Port Interfaces || sr_variables = {} try: df_sr = pd.read_excel(filename, sheet_name="SR Port Interfaces", header=None) df_sr0 = df_sr0.ffill() print(f"成功读取 'SR Port Interfaces' 工作表,共 {df_sr.shape0} 行,{df_sr.shape1} 列。") except ValueError as e: handle_error_and_exit(f"错误:未找到名为 'SR Port Interfaces' 的工作表。请检查 Excel 文件。") except Exception as e: handle_error_and_exit(f"错误:读取 'SR Port Interfaces' 工作表时发生未知错误:{e}") for idx, row in df_sr.iloc1:.iterrows(): task_orig = str(row0).strip() if pd.notna(row0) else "" var_name = str(row1).strip() if pd.notna(row1) else "" var_type = str(row2).strip() if pd.notna(row2) else "" comment = str(row3).strip() if pd.notna(row3) else "" if not task_orig or not var_name or not var_type: continue task_clean = sanitize_enum_name(task_orig) if task_clean not in raw_task_names: handle_error_and_exit(f"错误:SR Port Interfaces 中的任务名 '{task_orig}' 未在 Task 工作表中定义,生成终止。") if task_clean not in sr_variables: sr_variablestask_clean = \[\] sr_variablestask_clean.append((var_name, var_type, comment)) total_sr_vars = sum(len(v) for v in sr_variables.values()) if total_sr_vars == 0: print("警告:SR Port Interfaces 工作表中未找到有效变量定义(缺少任务名、变量名或变量类型)。") else: print(f"共收集到SR变量: {total_sr_vars} 个,分布在 {len(sr_variables)} 个任务中。") print("SR 变量详情:") for task, vars_list in sr_variables.items(): print(f" 任务 {task}: {len(vars_list)} 个变量") | |
| 17 | Data Types || data_types = {} try: df_dt = pd.read_excel(filename, sheet_name="Data Types", header=None) df_dt0 = df_dt0.ffill() print(f"成功读取 'Data Types' 工作表,共 {df_dt.shape0} 行,{df_dt.shape1} 列。") for idx, row in df_dt.iloc1:.iterrows(): task_orig = str(row0).strip() if pd.notna(row0) else "" type_def = str(row1).strip() if pd.notna(row1) else "" comment = str(row2).strip() if pd.notna(row2) else "" if not task_orig or not type_def: continue task_clean = sanitize_enum_name(task_orig) if task_clean not in data_types: data_typestask_clean = \[\] data_typestask_clean.append((type_def, comment)) print(f"共收集到数据类型定义: {sum(len(v) for v in data_types.values())} 个") except Exception as e: handle_error_and_exit(f"错误:读取 'Data Types' 工作表时出错:{e}") | |
| 18 | Task Queue || //Task Queue 读取Task Queue sheet页的数据 task_queues = {} try: df_tq = pd.read_excel(filename, sheet_name="Task Queue", header=None) df_tq0 = df_tq0.ffill() print(f"成功读取 'Task Queue' 工作表,共 {df_tq.shape0} 行,{df_tq.shape1} 列。") for idx, row in df_tq.iloc2:.iterrows(): task_orig = str(row0).strip() if pd.notna(row0) else "" msg_name = str(row1).strip() if pd.notna(row1) else "" data_type = str(row2).strip() if pd.notna(row2) else "" depth_cell = row3 try: depth = int(float(depth_cell)) if pd.notna(depth_cell) else 0 except: depth = 0 print(f"警告:消息 {msg_name} 队列深度不是有效数字,使用0") comment = str(row4).strip() if pd.notna(row4) else "" if not task_orig or not msg_name or not data_type or depth <= 0: print(f"警告:跳过无效消息定义: 任务={task_orig}, 消息={msg_name}, 类型={data_type}, 深度={depth}") continue task_clean = sanitize_enum_name(task_orig) if task_clean not in raw_task_names: handle_error_and_exit(f"错误:Task Queue 中的任务名 '{task_orig}' 未在 Task 工作表中定义,生成终止。") msg_var = sanitize_enum_name(msg_name) if task_clean not in task_queues: task_queuestask_clean = \[\] task_queuestask_clean.append((msg_var, data_type, depth, comment)) total_msgs = sum(len(v) for v in task_queues.values()) print(f"共收集到任务消息队列定义: {total_msgs} 个") except Exception as e: print(f"警告:读取 'Task Queue' 工作表时出错(可能不存在):{e}") | |
| 19 | rte.c || //rte 文件夹和文件的创建,以及头文件 1.创建rte文件夹和拼接rte_c_path = os.path.join(rte_dir, "rte.c") rte_c_path = os.path.join(rte_dir, "rte.c") rte_c_content = "" rte_c_content += '#include "rte.h"\n' rte_c_content += '#include "../bsw/osif/osif.h"\n' rte_c_content += '#include "../bsw/osif/osif_task.h"\n' rte_c_content += '#include "../bsw/osif/osif_task_cfg.h"\n' for task_name in orig_task_names: rte_c_content += f'#include "{task_name}swc.h"\n' rte_c_content += '\n' 2.生成任务线程函数 for i, task in enumerate(raw_task_names): task_camel = capitalize_first(task) task_upper = task.upper() task_lower = task func_body = f"""void {task_camel}ThreadInstant(void * param) {{ {task_lower}init_runnable(); while(1) {{ int i = 0; uint32_t eventflg = OSIF_TaskEventWait(TASK_ID{task_upper}); for(i = 0; i< 32; i++) {{ if(eventflg & (1UL<<i)) {{ if(i == EVT{task_upper}SLEEP) {{ stTaskCfgTblTASK_ID_{task_upper}.HostReqSlpFlag = 1; }} else if(i == EVT{task_upper}WAKEUP) {{ stTaskCfgTblTASK_ID_{task_upper}.HostReqSlpFlag = 0; }} if(stTaskCfgTblTASK_ID_{task_upper}.EventMapTablei) {{ stTaskCfgTblTASK_ID_{task_upper}.EventMapTablei(); }} }} }} }} }}""" | |
| 20 | rte.c || rte_c_content += func_body if i < len(raw_task_names) - 1: rte_c_content += '\n\n' rte_c_content += '\n' rte_c_content += 'void Rte_TaskCreate(void)\n' rte_c_content += '{\n' rte_c_content += ' /* Task Creation */\n' for task in raw_task_names: task_camel = capitalize_first(task) task_upper = task.upper() rte_c_content += f' OSIF_TaskCreate(TASK_ID{task_upper}, {task_camel}ThreadInstant, NULL);\n' rte_c_content += '\n' rte_c_content += ' /* Public Event Registration */\n' for i, task in enumerate(raw_task_names): row_idx = 2 + i task_camel = capitalize_first(task) task_upper = task.upper() for j, event in enumerate(common_suffixes): cell = df.ilocrow_idx, 5 + j # 公共事件从第6列(索引5)开始 is_true = False if pd.notna(cell): if isinstance(cell, bool): is_true = cell else: cell_str = str(cell).strip().upper() is_true = (cell_str == "TRUE") if is_true: rte_c_content += f' OSIF{task_camel}RegisterRunnable(EVT{task_upper}{event}, {task.lower()}{event.lower()}runnable);\n' rte_c_content += '\n' rte_c_content += ' /* Private Event Registration */\n' for i, task in enumerate(raw_task_names): task_camel = capitalize_first(task) task_upper = task.upper() for event in task_private_eventsi: rte_c_content += f' OSIF{task_camel}RegisterRunnable(EVT{task_upper}{event}, {task.lower()}{event.lower()}runnable);\n' rte_c_content += '\n /* Task Queue Creation */\n' for task in raw_task_names: if task in task_queues and len(task_queuestask) > 0: rte_c_content += f' rte_call{task}queue_create();\n' rte_c_content += '}\n' rte_c_content = add_file_trailer(rte_c_content, rte_c_path) if os.path.exists(rte_c_path): os.chmod(rte_c_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(rte_c_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(rte_c_content) print(f"成功创建文件 '{rte_c_path}'。") set_readonly(rte_c_path) except Exception as e: handle_error_and_exit(f"创建文件 '{rte_c_path}' 时发生错误:{e}") | |
| 21 | ret.h || rte_h_path = os.path.join(rte_dir, "rte.h") rte_h_content = "#ifndef RTE_H\n#define RTE_H\n\nvoid Rte_TaskCreate(void);\n\n#endif /* RTE_H */\n" rte_h_content = add_file_trailer(rte_h_content, rte_h_path) if os.path.exists(rte_h_path): os.chmod(rte_h_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(rte_h_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(rte_h_content) print(f"成功创建文件 '{rte_h_path}'。") set_readonly(rte_h_path) except Exception as e: handle_error_and_exit(f"创建文件 '{rte_h_path}' 时发生错误:{e}") | |
| 22 | app及其任务子文件夹 || 1.基于base_dir,创建app文件夹 app_dir = os.path.join(base_dir, "app") try: os.makedirs(app_dir, exist_ok=True) print(f"创建目录 '{app_dir}' 成功。") except Exception as e: handle_error_and_exit(f"创建目录 '{app_dir}' 时发生错误:{e}") 2.生成app_datatype.h app_datatype_h_path = os.path.join(app_dir, "app_datatype.h") app_datatype_content = """#ifndef APP_DATATYPE_H #define APP_DATATYPE_H #include <stdint.h> /* Data type definitions from all tasks */ """ # V1.6+: 数据类型不跟swc强绑定,直接输出所有 Data Types 工作表中的定义 if data_types: for task, type_list in data_types.items(): # 使用原始任务名作为分组标识(即使是 reserve) task_display = task.upper() if task != "reserve" else "COMMON" app_datatype_content += f"/*********** {task_display} Data Types ****************************/\n" for type_def, comment in type_list: if comment: app_datatype_content += f"/*********** {comment} *************/\n" app_datatype_content += f"{type_def}\n\n" app_datatype_content += "\n" else: app_datatype_content += "/* No data types defined in Excel */\n\n" app_datatype_content += "#endif /* APP_DATATYPE_H */\n" app_datatype_content = add_file_trailer(app_datatype_content, app_datatype_h_path) if os.path.exists(app_datatype_h_path): os.chmod(app_datatype_h_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(app_datatype_h_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(app_datatype_content) print(f"成功创建文件 '{app_datatype_h_path}'。") set_readonly(app_datatype_h_path) except Exception as e: handle_error_and_exit(f"创建文件 '{app_datatype_h_path}' 时发生错误:{e}") | |
| 23 | Host Power Manager || try: df_pm = pd.read_excel(filename, sheet_name="Host Power Manager", header=None) df_pm0 = df_pm0.ffill() print(f"成功读取 'Host Power Manager' 工作表,共 {df_pm.shape0} 行,{df_pm.shape1} 列。") except Exception as e: handle_error_and_exit(f"错误:读取 'Host Power Manager' 工作表时出错:{e}") enable_pm = False state_vars = \[\] decrease_vars = \[\] if df_pm.shape0 > 0 and df_pm.shape1 > 2: cell_val = df_pm.iloc0, 2 if pd.notna(cell_val): if isinstance(cell_val, bool): enable_pm = cell_val else: cell_str = str(cell_val).strip().upper() enable_pm = (cell_str == "TRUE") host_app_dir = os.path.join(app_dir, "host_app") if not enable_pm: for filename in "power_manager.c", "power_manager.h", "power_manager_port.c", "power_manager_port.h", "host_app.c": filepath = os.path.join(host_app_dir, filename) if os.path.isfile(filepath): try: os.remove(filepath) print(f"已删除文件 '{filepath}'。") except Exception as e: print(f"警告:删除文件 '{filepath}' 时出错:{e}") else: print(f"文件 '{filepath}' 不存在,无需删除。") else: if not os.path.exists(host_app_dir): try: os.makedirs(host_app_dir, exist_ok=True) print(f"创建目录 '{host_app_dir}' 成功。") except Exception as e: handle_error_and_exit(f"创建目录 '{host_app_dir}' 时发生错误:{e}") pm_vars = \[\] for idx, row in df_pm.iloc1:.iterrows(): if len(row) < 3: continue var_name = str(row0).strip() if pd.notna(row0) else "" var_type = str(row1).strip() if pd.notna(row1) else "" comment = str(row2).strip() if pd.notna(row2) else "" if var_name and var_type: pm_vars.append((var_name, var_type, comment)) state_vars = (name, comment) for name, var_type, comment in pm_vars if var_type and ("State" in str(var_type)) decrease_vars = (name, comment) for name, var_type, comment in pm_vars if var_type and ("Decrease" in str(var_type) or "Decreate" in str(var_type)) | |
| 24 | power_manager.h || //生成 power_manager.h h_path = os.path.join(host_app_dir, "power_manager.h") h_content = """#ifndef POWER_MANAGER_H #define POWER_MANAGER_H #include "wake_mgr.h" #include <stdint.h> /* 电源管理状态机 */ typedef enum { POWER_MODE_INIT, POWER_MODE_POWER_ON, POWER_MODE_NORMAL, POWER_MODE_RDY_TO_SUSPEND, POWER_MODE_SUSPEND, POWER_MODE_BAT_ERR, POWER_MODE_MAX } PowerMode_E; /* Enumeration definitions are in power_manager.c */ /* Function declarations */ void power_manager_decrease_var_process(uint32_t ulCycTime); void power_manager_machine_process(void); void power_manager_info_print(uint32_t ulPrintCycle); """ if state_vars: h_content += "\n/* State Var control functions */\n" for var_name, comment in state_vars: clean_name = sanitize_enum_name(var_name).lower() h_content += f"void power_manager_state_variate{clean_name}active(void);\n" h_content += f"void power_manager_state_variate{clean_name}deactive(void);\n" if decrease_vars: h_content += "\n/* Decrease Var control functions */\n" for var_name, comment in decrease_vars: clean_name = sanitize_enum_name(var_name).lower() h_content += f"void power_manager_decrease_variate{clean_name}active(uint32_t ulTimeMs);\n" h_content += "\n#endif /* POWER_MANAGER_H */\n" if os.path.exists(h_path): os.chmod(h_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(h_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(h_content) print(f"成功创建文件 '{h_path}'。") set_readonly(h_path) except Exception as e: handle_error_and_exit(f"写入文件 '{h_path}' 时发生错误:{e}") | |
| 25 | power_manager.c || c_path = os.path.join(host_app_dir, "power_manager.c") c_content_lines = \[\] c_content_lines.append('#include "power_manager.h"') c_content_lines.append('#include "wake_mgr.h"') c_content_lines.append('#include "string.h"') c_content_lines.append('#include "osif_task_cfg.h"') c_content_lines.append('#include "osif_task.h"') c_content_lines.append('#include "power_manager_port.h"') c_content_lines.append('#include "app_hook.h"') c_content_lines.append('#include "debug.h"') c_content_lines.append('') # State Var 枚举 c_content_lines.append("/* State Var enumeration */") c_content_lines.append("typedef enum") c_content_lines.append("{") if state_vars: for var_name, comment in state_vars: clean_name = sanitize_enum_name(var_name).upper() c_content_lines.append(f"\tHOST_WAKEUP_MGR_STATE_VAR{clean_name}, /* {comment} */") c_content_lines.append("\tHOST_WAKEUP_MGR_STATE_VAR_MAX") c_content_lines.append("} HostWakeupMgrStateVar_E;") c_content_lines.append("") # Decrease Var 枚举 if decrease_vars: c_content_lines.append("/* Decrease Var enumeration */") c_content_lines.append("typedef enum") c_content_lines.append("{") for i, (var_name, comment) in enumerate(decrease_vars): clean_name = sanitize_enum_name(var_name).upper() if i == 0: c_content_lines.append( f"\tHOST_WAKEUP_MGR_DECREASE{clean_name} = HOST_WAKEUP_MGR_STATE_VAR_MAX, /* {comment} */") else: c_content_lines.append(f"\tHOST_WAKEUP_MGR_DECREASE{clean_name}, /* {comment} */") c_content_lines.append("\tHOST_WAKEUP_MGR_DECREASE_MAX") c_content_lines.append("} HostWakeupMgrDecreaseVar_E;") c_content_lines.append("") # 变量名字符串数组 if state_vars or decrease_vars: c_content_lines.append("/* Variable name lookup table */") if decrease_vars: c_content_lines.append("const char* achHostWakeupMgrVarNameHOST_WAKEUP_MGR_DECREASE_MAX =") c_content_lines.append("#define HOST_POWER_MGR_VAR_COUNT HOST_WAKEUP_MGR_DECREASE_MAX") else: c_content_lines.append("const char* achHostWakeupMgrVarNameHOST_WAKEUP_MGR_STATE_VAR_MAX =") c_content_lines.append("#define HOST_POWER_MGR_VAR_COUNT HOST_WAKEUP_MGR_STATE_VAR_MAX") c_content_lines.append("{") for var_name, comment in state_vars: clean_name = sanitize_enum_name(var_name).upper() c_content_lines.append(f"\tHOST_WAKEUP_MGR_STATE_VAR_{clean_name} = \"{var_name}\",") for var_name, comment in decrease_vars: clean_name = sanitize_enum_name(var_name).upper() c_content_lines.append(f"\tHOST_WAKEUP_MGR_DECREASE_{clean_name} = \"{var_name}\",") c_content_lines.append("};") c_content_lines.append("") else: c_content_lines.append("const char* achHostWakeupMgrVarName1 = {0};") c_content_lines.append("#define HOST_POWER_MGR_VAR_COUNT 1") c_content_lines.append("") # 电源管理状态机字符串数组 c_content_lines.append("static const char * powerModeStrPOWER_MODE_MAX = ") c_content_lines.append("{") c_content_lines.append(" POWER_MODE_INIT = \"Init\",") c_content_lines.append(" POWER_MODE_POWER_ON = \"PowerOn\",") c_content_lines.append(" POWER_MODE_NORMAL = \"Normal\",") c_content_lines.append(" POWER_MODE_RDY_TO_SUSPEND = \"RdyToSuspend\",") c_content_lines.append(" POWER_MODE_SUSPEND = \"Suspend\",") c_content_lines.append(" POWER_MODE_BAT_ERR = \"BatErr\",") c_content_lines.append("};") c_content_lines.append("") c_content_lines.append("static volatile WAKEUP_MGR_ST s_stHostWakeupMgr;") c_content_lines.append("static volatile PowerMode_E s_ePowerMode = POWER_MODE_INIT;") c_content_lines.append("") # 添加 power_manager_decrease_var_process 函数定义 c_content_lines.append("/**") c_content_lines.append(" * @brief 周期性处理递减变量") c_content_lines.append(" * ") c_content_lines.append(" * @param ulCycTime ") c_content_lines.append(" */") c_content_lines.append("void power_manager_decrease_var_process(uint32_t ulCycTime)") c_content_lines.append("{") c_content_lines.append(" WakeupMgr_MachineProc((WAKEUP_MGR_ST*)&s_stHostWakeupMgr, ulCycTime);") c_content_lines.append("}") c_content_lines.append("") # 生成 State Var 的 active/deactive 函数 if state_vars: c_content_lines.append("/* State Var control functions */") for var_name, comment in state_vars: clean_name_lower = sanitize_enum_name(var_name).lower() clean_name_upper = sanitize_enum_name(var_name).upper() c_content_lines.append("/**") c_content_lines.append(f" * @brief {comment}") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append(f"void power_manager_state_variate{clean_name_lower}active(void)") c_content_lines.append("{") c_content_lines.append( f" WakeupMgr_active_state_variate((WAKEUP_MGR_ST*)&s_stHostWakeupMgr, HOST_WAKEUP_MGR_STATE_VAR{clean_name_upper});") c_content_lines.append("}") c_content_lines.append("") c_content_lines.append("/**") c_content_lines.append(f" * @brief {comment}") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append(f"void power_manager_state_variate{clean_name_lower}deactive(void)") c_content_lines.append("{") c_content_lines.append( f" WakeupMgr_deactive_state_variate((WAKEUP_MGR_ST*)&s_stHostWakeupMgr, HOST_WAKEUP_MGR_STATE_VAR{clean_name_upper});") c_content_lines.append("}") c_content_lines.append("") # 生成 Decrease Var 的 active 函数 if decrease_vars: c_content_lines.append("/* Decrease Var control functions */") for var_name, comment in decrease_vars: clean_name_lower = sanitize_enum_name(var_name).lower() clean_name_upper = sanitize_enum_name(var_name).upper() c_content_lines.append("/**") c_content_lines.append(f" * @brief {comment}") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append( f"void power_manager_decrease_variate{clean_name_lower}active(uint32_t ulTimeMs)") c_content_lines.append("{") c_content_lines.append( f" WakeupMgr_active_decrease_variate((WAKEUP_MGR_ST*)&s_stHostWakeupMgr, HOST_WAKEUP_MGR_DECREASE{clean_name_upper}, ulTimeMs);") c_content_lines.append("}") c_content_lines.append("") # 添加 power_mode_change 静态函数 c_content_lines.append("") c_content_lines.append("/**") c_content_lines.append(" * @brief 电源状态切换处理") c_content_lines.append(" * ") c_content_lines.append(" * @param newSate ") c_content_lines.append(" */") c_content_lines.append("static void power_mode_change(PowerMode_E newSate)") c_content_lines.append("{") c_content_lines.append("\tif(s_ePowerMode != newSate)") c_content_lines.append(" {") c_content_lines.append(" power_manager_change_notify(newSate,s_ePowerMode,powerModeStr);") c_content_lines.append(" s_ePowerMode = newSate;") c_content_lines.append("\t}") c_content_lines.append("}") c_content_lines.append("") # 添加新的静态函数 power_manager_excute_system_into_sleep(带参) c_content_lines.append("/**") c_content_lines.append(" * @brief 执行系统休眠,注意:该函数是在关中断的临界区下执行!!!") c_content_lines.append(" * ") c_content_lines.append(" * @param newSate ") c_content_lines.append(" */") c_content_lines.append("static void power_manager_excute_system_into_sleep(PowerMode_E newSate)") c_content_lines.append("{") c_content_lines.append( " /* 进入临界区的状态下二次判断,防止上一级业务 判断 WakeupMgr_IsActive 满足休眠条件,进入 power_manager_excute_system_into_sleep后") c_content_lines.append( " 在执行WFI之前发生中断,导致走了WIFI休眠后没被唤醒 。 注意 power_manager_excute_system_into_sleep 是在临界区下执行的*/") c_content_lines.append(" uint32_t saveVar = 0;") c_content_lines.append(" OSIF_UNIFIED_ENTER_CRITICAL(saveVar);") c_content_lines.append(" if(!WakeupMgr_IsActive((WAKEUP_MGR_ST*)&s_stHostWakeupMgr))") c_content_lines.append(" {") c_content_lines.append(" power_manager_excute_system_into_sleep_port();") c_content_lines.append(" }") c_content_lines.append(" OSIF_UNIFIED_EXIT_CRITICAL(saveVar);") c_content_lines.append("}") c_content_lines.append("") # 添加电源状态机管理函数 c_content_lines.append("/**") c_content_lines.append(" * @brief 电源状态机迁移管理") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append("void power_manager_machine_process(void)") c_content_lines.append("{") c_content_lines.append("\tswitch(s_ePowerMode)") c_content_lines.append("\t{") c_content_lines.append(" case POWER_MODE_INIT:") c_content_lines.append(" {") c_content_lines.append( " // TODO : 一般要求,高低压判断,超低压或者超高压不做启动,对外表现,CAN NM不做通讯,BLE 不工作 。") c_content_lines.append(" // 电压正常的情况下,才发送开机事件。") c_content_lines.append(" power_mode_change(POWER_MODE_POWER_ON);") c_content_lines.append(" OSIF_TaskEventBroadcast(EVT_COMMON_POWER_ON);") c_content_lines.append(" }break;") c_content_lines.append("") c_content_lines.append(" case POWER_MODE_POWER_ON:") c_content_lines.append(" {") c_content_lines.append( " // host 任务初始化需调用 HostWakeupMgr_decrease_variate_poweron_active让系统运行一段时间后在进入休眠;") c_content_lines.append(" power_mode_change(POWER_MODE_NORMAL);") c_content_lines.append(" } ") c_content_lines.append("\t\t\tbreak;") c_content_lines.append("") c_content_lines.append(" case POWER_MODE_NORMAL:") c_content_lines.append(" // 判断当前是否存在系统唤醒的需求,如果没有则进入准备休眠流程") c_content_lines.append("\t\t\tif(!WakeupMgr_IsActive((WAKEUP_MGR_ST*)&s_stHostWakeupMgr))") c_content_lines.append(" {") c_content_lines.append("\t\t\t\tpower_mode_change(POWER_MODE_RDY_TO_SUSPEND);") c_content_lines.append(" OSIF_TaskEventBroadcast(EVT_COMMON_SLEEP);") c_content_lines.append("\t\t\t}") c_content_lines.append("\t\t\tbreak;") c_content_lines.append("") c_content_lines.append(" case POWER_MODE_RDY_TO_SUSPEND:") c_content_lines.append(" // 判断当前是否存在系统唤醒的需求,如果有则走唤醒流程") c_content_lines.append("\t\t\tif(WakeupMgr_IsActive((WAKEUP_MGR_ST*)&s_stHostWakeupMgr))") c_content_lines.append(" {") c_content_lines.append("\t\t\t\tpower_mode_change(POWER_MODE_NORMAL);") c_content_lines.append(" OSIF_TaskEventBroadcast(EVT_COMMON_WAKEUP);") c_content_lines.append("\t\t\t}") c_content_lines.append(" // 判断当前是不是所有的任务都回了休眠确认,是则整机进入休眠流程") c_content_lines.append("\t\t\telse if(OSIF_IsAllAppTaskSuspend(TASK_ID_HOST))") c_content_lines.append(" {") c_content_lines.append("\t\t\t\tpower_mode_change(POWER_MODE_SUSPEND);") c_content_lines.append("\t\t\t}") c_content_lines.append("\t\t\tbreak;") c_content_lines.append("") c_content_lines.append(" case POWER_MODE_SUSPEND:") c_content_lines.append(" // 判断当前是否存在系统唤醒的需求,如果有则中断当前流程") c_content_lines.append("\t\t\tif(WakeupMgr_IsActive((WAKEUP_MGR_ST*)&s_stHostWakeupMgr))") c_content_lines.append(" {") c_content_lines.append("\t\t\t\tpower_mode_change(POWER_MODE_NORMAL);") c_content_lines.append(" OSIF_TaskEventBroadcast(EVT_COMMON_WAKEUP);") c_content_lines.append("\t\t\t}") c_content_lines.append(" else") c_content_lines.append(" {") c_content_lines.append(" power_manager_excute_system_into_sleep(POWER_MODE_SUSPEND);") c_content_lines.append(" if(WakeupMgr_IsActive((WAKEUP_MGR_ST*)&s_stHostWakeupMgr))") c_content_lines.append(" {") c_content_lines.append(" power_mode_change(POWER_MODE_NORMAL);") c_content_lines.append(" OSIF_TaskEventBroadcast(EVT_COMMON_WAKEUP);") c_content_lines.append(" }") c_content_lines.append(" ") c_content_lines.append(" }") c_content_lines.append("\t\t\tbreak;") c_content_lines.append("") c_content_lines.append(" case POWER_MODE_BAT_ERR:") c_content_lines.append(" // TODO : 增加电源电压异常处理") c_content_lines.append("\t\t\tbreak;") c_content_lines.append("") c_content_lines.append("") c_content_lines.append("\t\tdefault:") c_content_lines.append("\t\t\tbreak;") c_content_lines.append("\t}") c_content_lines.append("}") c_content_lines.append("") # 添加 power_manager_info_print 函数 c_content_lines.append("/**") c_content_lines.append(" * @brief 周期性打印状态机") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append("void power_manager_info_print(uint32_t ulPrintCycle)") c_content_lines.append("{") c_content_lines.append(" uint8_t i;") c_content_lines.append(" static uint32_t s_ulTick;") c_content_lines.append("") c_content_lines.append(" if(s_ulTick == 0 || ") c_content_lines.append(" ((OSIF_GetMilliseconds() - s_ulTick) >= ulPrintCycle)") c_content_lines.append(" )") c_content_lines.append(" {") c_content_lines.append(" uint32_t saveVar = 0;") c_content_lines.append(" WAKEUP_MGR_ST stHostWakeuoMgrTmp = {0};") c_content_lines.append(" s_ulTick = OSIF_GetMilliseconds();") c_content_lines.append("\t\t\t\t") c_content_lines.append(" OSIF_UNIFIED_ENTER_CRITICAL(saveVar);") c_content_lines.append( " memcpy(&stHostWakeuoMgrTmp, (const void*)&s_stHostWakeupMgr, sizeof(WAKEUP_MGR_ST));") c_content_lines.append(" OSIF_UNIFIED_EXIT_CRITICAL(saveVar);") c_content_lines.append("") c_content_lines.append(" LOG_INFO(\"Power Manager Info:\\r\\n\");") c_content_lines.append(" for(i = 0; i < HOST_POWER_MGR_VAR_COUNT; i++)") c_content_lines.append(" {") c_content_lines.append( " LOG_INFO(\"%s:%d\\r\\n\", achHostWakeupMgrVarNamei, stHostWakeuoMgrTmp.ulTicksi);") c_content_lines.append(" }") c_content_lines.append(" }") c_content_lines.append("}") c_content = "\n".join(c_content_lines) + "\n" if os.path.exists(c_path): os.chmod(c_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(c_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(c_content) print(f"成功创建文件 '{c_path}'。") set_readonly(c_path) except Exception as e: handle_error_and_exit(f"写入文件 '{c_path}' 时发生错误:{e}") | |
| 26 | power_manager_port.h || //生成 power_manager_port.h port_h_path = os.path.join(host_app_dir, "power_manager_port.h") port_h_content = """#ifndef POWER_MANAGER_PORT_H #define POWER_MANAGER_PORT_H #include <stdint.h> #include "power_manager.h" #include "app_hook.h" /* User code */ /* Porting layer for power management */ void power_manager_change_notify(PowerMode_E NewSate, PowerMode_E CurrentSate, const char **StateName); void power_manager_excute_system_into_sleep_port(void); #endif /* POWER_MANAGER_PORT_H */ """ if os.path.exists(port_h_path): os.chmod(port_h_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(port_h_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(port_h_content) print(f"成功创建文件 '{port_h_path}'。") set_readonly(port_h_path) except Exception as e: handle_error_and_exit(f"写入文件 '{port_h_path}' 时发生错误:{e}") | |
| 27 | power_manager_port.c || port_c_path = os.path.join(host_app_dir, "power_manager_port.c") port_c_content = """#include "power_manager_port.h" #include "power_manager.h" #include "../../bsw/compiler_compat.h" /** * @brief 电源状态切换函数 * * @param NewSate * @param CurrentSate * @param StateName * @note 此函数为弱定义,用户可在自己的文件中重定义 */ COMPAT_WEAK_DEF void power_manager_change_notify(PowerMode_E NewSate, PowerMode_E CurrentSate, const char **StateName) { } /** * @brief 执行系统休眠,注意:该函数是在关中断的临界区下执行!!! * * @note 此函数为弱定义,用户可在自己的文件中重定义 */ COMPAT_WEAK_DEF void power_manager_excute_system_into_sleep_port(void) { } """ if os.path.exists(port_c_path): os.chmod(port_c_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(port_c_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(port_c_content) print(f"成功创建文件 '{port_c_path}'。") set_readonly(port_c_path) except Exception as e: handle_error_and_exit(f"写入文件 '{port_c_path}' 时发生错误:{e}") host_app_c_path = os.path.join(host_app_dir, "host_app.c") if os.path.isfile(host_app_c_path): try: os.remove(host_app_c_path) print(f"已删除文件 '{host_app_c_path}'(内容已整合到 power_manager.c)。") except Exception as e: print(f"警告:删除文件 '{host_app_c_path}' 时出错:{e}") | |
| 28 | || //处理采集 CANx NetWork Manager sheet页数据 can_nm_pattern = re.compile(r'^CAN(\d+)\s+Network\s+Manager(\(.*\))?$') try: xl = pd.ExcelFile(filename) can_nm_sheets = \[\] for sheet in xl.sheet_names: match = can_nm_pattern.match(sheet.strip()) if match: can_num = int(match.group(1)) can_nm_sheets.append((sheet, can_num)) if can_nm_sheets: print(f"发现 {len(can_nm_sheets)} 个 CAN Network Manager 工作表: {s\[0 for s in can_nm_sheets]}") else: print("未发现 CAN Network Manager 工作表,跳过处理。") except Exception as e: print(f"获取工作表列表时出错: {e}") can_nm_sheets = \[\] # 存储所有CAN NM的信息,供后续生成任务文件时使用 can_nm_data_list = \[\] # 每个元素: (can_num, enable_nm, nm_vars, state_vars, decrease_vars) for sheet_name, can_num in can_nm_sheets: print(f"\n--- 处理 CAN{can_num} Network Manager 工作表 ---") try: df_can_nm = pd.read_excel(filename, sheet_name=sheet_name, header=None) df_can_nm0 = df_can_nm0.ffill() print(f"成功读取 '{sheet_name}' 工作表,共 {df_can_nm.shape0} 行,{df_can_nm.shape1} 列。") except Exception as e: print(f"错误:读取 '{sheet_name}' 工作表时出错:{e}") continue enable_nm = False nm_module_name = f"can{can_num}nm_manager" # 默认模块名称 nm_state_vars = \[\] nm_decrease_vars = \[\] # 读取模块名称(第0行第2列)和启用标志(第1行第2列) if df_can_nm.shape0 > 0 and df_can_nm.shape1 > 2: # 读取模块名称 module_name_val = df_can_nm.iloc0, 2 if pd.notna(module_name_val): nm_module_name = str(module_name_val).strip() print(f"模块名称: {nm_module_name}") # 读取启用标志(第1行第2列) if df_can_nm.shape0 > 1: cell_val = df_can_nm.iloc1, 2 if pd.notna(cell_val): if isinstance(cell_val, bool): enable_nm = cell_val else: cell_str = str(cell_val).strip().upper() enable_nm = (cell_str == "TRUE") print(f"启用标志: {enable_nm} (原始值: {repr(cell_val)})") # 使用模块名称创建安全的文件名(替换特殊字符) safe_module_name = re.sub(r'\^a-zA-Z0-9_', '', nm_module_name) # 使用can_app目录,不创建单独的文件夹 can_nm_dir = os.path.join(app_dir, "can_app") # 先解析变量(无论是否启用,都需要变量信息来生成rte_call接口) nm_vars = \[\] for idx, row in df_can_nm.iloc1:.iterrows(): if len(row) < 3: continue var_name = str(row0).strip() if pd.notna(row0) else "" var_type = str(row1).strip() if pd.notna(row1) else "" comment = str(row2).strip() if pd.notna(row2) else "" if var_name and var_type: nm_vars.append((var_name, var_type, comment)) # 匹配 State Var / Decrease Var(兼容 "Decreate Var" 等常见拼写错误) nm_state_vars = (name, comment) for name, var_type, comment in nm_vars if var_type and ("State" in str(var_type)) nm_decrease_vars = (name, comment) for name, var_type, comment in nm_vars if var_type and ("Decrease" in str(var_type) or "Decreate" in str(var_type)) if not enable_nm: print(f"{nm_module_name} (CAN{can_num}) 未启用,跳过文件生成。") # 如果文件存在,清理相关文件 if os.path.exists(can_nm_dir): for filename in f"{safe_module_name}.c", f"{safe_module_name}.h": filepath = os.path.join(can_nm_dir, filename) if os.path.isfile(filepath): try: os.remove(filepath) print(f"已删除文件 '{filepath}'。") except Exception as e: print(f"警告:删除文件 '{filepath}' 时出错:{e}") can_nm_data_list.append((can_num, False, nm_module_name, nm_vars, nm_state_vars, nm_decrease_vars)) else: print(f"{nm_module_name} (CAN{can_num}) 已启用,开始生成文件...") if not os.path.exists(can_nm_dir): try: os.makedirs(can_nm_dir, exist_ok=True) print(f"创建目录 '{can_nm_dir}' 成功。") except Exception as e: handle_error_and_exit(f"创建目录 '{can_nm_dir}' 时发生错误:{e}") can_nm_data_list.append((can_num, True, nm_module_name, nm_vars, nm_state_vars, nm_decrease_vars)) # ========== 生成 {module_name}.h ========== h_path = os.path.join(can_nm_dir, f"{safe_module_name}.h") # 生成大写版本的模块名称用于宏定义 module_name_upper = safe_module_name.upper() module_name_camel = safe_module_name.title().replace('_', '') h_content = f"""#ifndef {module_name_upper}_H #define {module_name_upper}_H #include "wake_mgr.h" #include <stdint.h> #include <stdbool.h> /* Handler function type for NM request handling */ typedef void (*{safe_module_name}_req_handler_t)(bool is_active); /* Function declarations */ void {safe_module_name}_decrease_var_process(uint32_t ulCycTime); void {safe_module_name}_check_and_handle(void); void {safe_module_name}_info_print(uint32_t ulPrintCycle); void {safe_module_name}_register_req_handler({safe_module_name}_req_handler_t handler); """ if nm_state_vars: h_content += "\n/* State Var control functions */\n" for var_name, comment in nm_state_vars: clean_name = sanitize_enum_name(var_name).lower() h_content += f"void {safe_module_name}state_variate{clean_name}_active(void);\n" h_content += f"void {safe_module_name}state_variate{clean_name}_deactive(void);\n" if nm_decrease_vars: h_content += "\n/* Decrease Var control functions */\n" for var_name, comment in nm_decrease_vars: clean_name = sanitize_enum_name(var_name).lower() h_content += f"void {safe_module_name}decrease_variate{clean_name}_active(uint32_t ulTimeMs);\n" h_content += f"\n#endif /* {module_name_upper}_H */\n" if os.path.exists(h_path): os.chmod(h_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(h_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(h_content) print(f"成功创建文件 '{h_path}'。") set_readonly(h_path) except Exception as e: handle_error_and_exit(f"写入文件 '{h_path}' 时发生错误:{e}") # ========== 生成 {module_name}.c ========== c_path = os.path.join(can_nm_dir, f"{safe_module_name}.c") c_content_lines = \[\] c_content_lines.append(f'#include "{safe_module_name}.h"') c_content_lines.append('#include "wake_mgr.h"') c_content_lines.append('#include "string.h"') c_content_lines.append('#include "osif_task_cfg.h"') c_content_lines.append('#include "osif_task.h"') c_content_lines.append('#include "app_hook.h"') c_content_lines.append('#include "debug.h"') c_content_lines.append('') # State Var 枚举 c_content_lines.append("/* State Var enumeration */") c_content_lines.append("typedef enum") c_content_lines.append("{") if nm_state_vars: for var_name, comment in nm_state_vars: clean_name = sanitize_enum_name(var_name).upper() c_content_lines.append(f"\t{module_name_upper}STATE_VAR{clean_name}, /* {comment} */") c_content_lines.append(f"\t{module_name_upper}_STATE_VAR_MAX") c_content_lines.append(f"}} {module_name_camel}StateVar_E;") c_content_lines.append("") # Decrease Var 枚举 if nm_decrease_vars: c_content_lines.append("/* Decrease Var enumeration */") c_content_lines.append("typedef enum") c_content_lines.append("{") for i, (var_name, comment) in enumerate(nm_decrease_vars): clean_name = sanitize_enum_name(var_name).upper() if i == 0: c_content_lines.append( f"\t{module_name_upper}DECREASE{clean_name} = {module_name_upper}_STATE_VAR_MAX, /* {comment} */") else: c_content_lines.append(f"\t{module_name_upper}DECREASE{clean_name}, /* {comment} */") c_content_lines.append(f"\t{module_name_upper}_DECREASE_MAX") c_content_lines.append(f"}} {module_name_camel}DecreaseVar_E;") c_content_lines.append("") # 变量名字符串数组 if nm_state_vars or nm_decrease_vars: c_content_lines.append("/* Variable name lookup table */") if nm_decrease_vars: c_content_lines.append(f"const char* ach{module_name_camel}VarName{module_name_upper}_DECREASE_MAX =") c_content_lines.append(f"#define {module_name_upper}_VAR_COUNT {module_name_upper}_DECREASE_MAX") else: c_content_lines.append(f"const char* ach{module_name_camel}VarName{module_name_upper}_STATE_VAR_MAX =") c_content_lines.append(f"#define {module_name_upper}_VAR_COUNT {module_name_upper}_STATE_VAR_MAX") c_content_lines.append("{") for var_name, comment in nm_state_vars: clean_name = sanitize_enum_name(var_name).upper() c_content_lines.append(f"\t{module_name_upper}_STATE_VAR_{clean_name} = \"{var_name}\",") for var_name, comment in nm_decrease_vars: clean_name = sanitize_enum_name(var_name).upper() c_content_lines.append(f"\t{module_name_upper}_DECREASE_{clean_name} = \"{var_name}\",") c_content_lines.append("};") c_content_lines.append("") else: c_content_lines.append(f"const char* ach{module_name_camel}VarName1 = {{0}};") c_content_lines.append(f"#define {module_name_upper}_VAR_COUNT 1") c_content_lines.append("") c_content_lines.append(f"static volatile WAKEUP_MGR_ST s_st{module_name_camel}WakeupMgr;") c_content_lines.append(f"static volatile bool s_b{module_name_camel}LastActive = false;") c_content_lines.append(f"static {safe_module_name}req_handler_t s{safe_module_name}_req_handler = NULL;") c_content_lines.append("") # 添加 {safe_module_name}_decrease_var_process 函数定义 c_content_lines.append("/**") c_content_lines.append(f" * @brief {nm_module_name} 周期性处理递减变量") c_content_lines.append(" * ") c_content_lines.append(" * @param ulCycTime ") c_content_lines.append(" */") c_content_lines.append(f"void {safe_module_name}_decrease_var_process(uint32_t ulCycTime)") c_content_lines.append("{") c_content_lines.append( f" WakeupMgr_MachineProc((WAKEUP_MGR_ST*)&s_st{module_name_camel}WakeupMgr, ulCycTime);") c_content_lines.append("}") c_content_lines.append("") # 生成 State Var 的 active/deactive 函数 if nm_state_vars: c_content_lines.append("/* State Var control functions */") for var_name, comment in nm_state_vars: clean_name_lower = sanitize_enum_name(var_name).lower() clean_name_upper = sanitize_enum_name(var_name).upper() c_content_lines.append("/**") c_content_lines.append(f" * @brief {comment}") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append( f"void {safe_module_name}state_variate{clean_name_lower}_active(void)") c_content_lines.append("{") c_content_lines.append( f" WakeupMgr_active_state_variate((WAKEUP_MGR_ST*)&s_st{module_name_camel}WakeupMgr, {module_name_upper}STATE_VAR{clean_name_upper});") c_content_lines.append("}") c_content_lines.append("") c_content_lines.append("/**") c_content_lines.append(f" * @brief {comment}") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append( f"void {safe_module_name}state_variate{clean_name_lower}_deactive(void)") c_content_lines.append("{") c_content_lines.append( f" WakeupMgr_deactive_state_variate((WAKEUP_MGR_ST*)&s_st{module_name_camel}WakeupMgr, {module_name_upper}STATE_VAR{clean_name_upper});") c_content_lines.append("}") c_content_lines.append("") c_content_lines.append("") # 生成 Decrease Var 的 active 函数 if nm_decrease_vars: c_content_lines.append("/* Decrease Var control functions */") for var_name, comment in nm_decrease_vars: clean_name_lower = sanitize_enum_name(var_name).lower() clean_name_upper = sanitize_enum_name(var_name).upper() c_content_lines.append("/**") c_content_lines.append(f" * @brief {comment}") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append( f"void {safe_module_name}decrease_variate{clean_name_lower}_active(uint32_t ulTimeMs)") c_content_lines.append("{") c_content_lines.append( f" WakeupMgr_active_decrease_variate((WAKEUP_MGR_ST*)&s_st{module_name_camel}WakeupMgr, {module_name_upper}DECREASE{clean_name_upper}, ulTimeMs);") c_content_lines.append("}") c_content_lines.append("") c_content_lines.append("") # 添加 {safe_module_name}_register_req_handler 函数 c_content_lines.append("/**") c_content_lines.append(f" * @brief 注册{safe_module_name}的请求处理回调函数") c_content_lines.append(" * ") c_content_lines.append(f" * @param handler 回调函数指针,原型: void handler(bool is_active)") c_content_lines.append(" */") c_content_lines.append(f"void {safe_module_name}_register_req_handler({safe_module_name}req_handler_t handler)") c_content_lines.append("{") c_content_lines.append(f" s{safe_module_name}_req_handler = handler;") c_content_lines.append("}") c_content_lines.append("") # 添加 {safe_module_name}_check_and_handle 函数 c_content_lines.append("") c_content_lines.append("/**") c_content_lines.append(f" * @brief {nm_module_name} 检查唤醒请求并处理") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append(f"void {safe_module_name}check_and_handle(void)") c_content_lines.append("{") c_content_lines.append(f" bool is_active = WakeupMgr_IsActive((WAKEUP_MGR_ST*)&s_st{module_name_camel}WakeupMgr);") c_content_lines.append(f" if(is_active != s_b{module_name_camel}LastActive)") c_content_lines.append(" {") c_content_lines.append(f" s_b{module_name_camel}LastActive = is_active;") c_content_lines.append(f" if(s{safe_module_name}req_handler != NULL)") c_content_lines.append(" {") c_content_lines.append(f" s{safe_module_name}_req_handler(is_active);") c_content_lines.append(" }") c_content_lines.append(" }") c_content_lines.append("}") c_content_lines.append("") # 添加 {safe_module_name}_info_print 函数 c_content_lines.append("/**") c_content_lines.append(f" * @brief {nm_module_name} 周期性打印状态机信息") c_content_lines.append(" * ") c_content_lines.append(" */") c_content_lines.append(f"void {safe_module_name}_info_print(uint32_t ulPrintCycle)") c_content_lines.append("{") c_content_lines.append(" uint8_t i;") c_content_lines.append(" static uint32_t s_ulTick;") c_content_lines.append("") c_content_lines.append(" if(s_ulTick == 0 || ") c_content_lines.append(" ((OSIF_GetMilliseconds() - s_ulTick) >= ulPrintCycle)") c_content_lines.append(" )") c_content_lines.append(" {") c_content_lines.append(" uint32_t saveVar = 0;") c_content_lines.append(f" WAKEUP_MGR_ST st{module_name_camel}WakeuoMgrTmp = {{0}};") c_content_lines.append(" s_ulTick = OSIF_GetMilliseconds();") c_content_lines.append("\t\t\t\t") c_content_lines.append(" OSIF_UNIFIED_ENTER_CRITICAL(saveVar);") c_content_lines.append( f" memcpy(&st{module_name_camel}WakeuoMgrTmp, (const void*)&s_st{module_name_camel}WakeupMgr, sizeof(WAKEUP_MGR_ST));") c_content_lines.append(" OSIF_UNIFIED_EXIT_CRITICAL(saveVar);") c_content_lines.append("") c_content_lines.append(f" LOG_INFO(\"{nm_module_name} NM Info:\\r\\n\");") c_content_lines.append(f" for(i = 0; i < {module_name_upper}_VAR_COUNT; i++)") c_content_lines.append(" {") c_content_lines.append( f" LOG_INFO(\"%s:%d\\r\\n\", ach{module_name_camel}VarNamei, st{module_name_camel}WakeuoMgrTmp.ulTicksi);") c_content_lines.append(" }") c_content_lines.append(" }") c_content_lines.append("}") c_content = "\n".join(c_content_lines) + "\n" if os.path.exists(c_path): os.chmod(c_path, stat.S_IWRITE | stat.S_IRUSR | stat._IRGRP | stat.S_IROTH) try: with open(c_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(c_content) print(f"成功创建文件 '{c_path}'。") set_readonly(c_path) except Exception as e: handle_error_and_exit(f"写入文件 '{c_path}' 时发生错误:{e}") | |
| 29 | {task}_swc.c {task}_swc.h || for i, task in enumerate(raw_task_names): task_dir = os.path.join(app_dir, f"{task}app") try: os.makedirs(task_dir, exist_ok=True) print(f"创建目录 '{task_dir}' 成功。") except Exception as e: handle_error_and_exit(f"创建目录 '{task_dir}' 时发生错误:{e}") private_events = event.lower() for event in task_private_events\[i] public_events = \[\] row_idx = 2 + i for j, event in enumerate(common_suffixes): cell = df.ilocrow_idx, 5 + j is_registered = False if pd.notna(cell): if isinstance(cell, bool): is_registered = cell else: cell_str = str(cell).strip().upper() is_registered = (cell_str == "TRUE") if is_registered: public_events.append(event.lower()) events = public_events + private_events # 生成头文件 {task}swc.h header_file_path = os.path.join(task_dir, f"{task}swc.h") header_content = f"""#ifndef {task.upper()}SW_H #define {task.upper()}SW_H #include <stdint.h> #include "../../bsw/osif/osif_task.h" #include "../app_datatype.h" """ header_content += f"/* Event function declarations for {task} task */\n\n" for event in events: header_content += f"void {task}{event}runnable(void);\n" header_content += f"\n/* Initialization function */\n" header_content += f"void {task}init_runnable(void);\n" task_camel = capitalize_first(task) header_content += f"\n/* Event send function */\n" header_content += f"void rte_call_send{task}task_event({task_camel}Evt_E e{task_camel}Evt);\n" header_content += "\n/* Interface function declarations */\n" if task in interface_functions: for decl, desc in interface_functionstask: if desc: header_content += f"/**\n * {desc}\n */\n" decl_clean = decl.strip() if not decl_clean.endswith(';'): decl_clean += ';' header_content += f"{decl_clean}\n" if task in sr_variables: header_content += "\n/* SR Port Interface Functions */\n" for var_name, var_type, comment in sr_variablestask: if comment: header_content += f"/* {comment} */\n" header_content += f"void rte_write{var_name}({var_type}* param);\n" header_content += f"void rte_read{var_name}({var_type} *param);\n" if task in task_queues and len(task_queuestask) > 0: header_content += f"\n/* Task Queue Functions */\n" header_content += f"void rte_call{task}queue_create(void);\n" # 添加发送函数声明 for msg_var, data_type, depth, comment in task_queuestask: header_content += f"uint8_t rte_call_send{task}{msg_var}({data_type} *pQItem);\n" if task == "host" and enable_pm: if state_vars: for var_name, comment in state_vars: clean_name = sanitize_enum_name(var_name).lower() header_content += f"\n/* Auto Create From Host Power Manager */\n" header_content += f"void rte_call_host_power_manager_state_variate{clean_name}active(void);\n" header_content += f"void rte_call_host_power_manager_state_variate{clean_name}deactive(void);\n" if decrease_vars: for var_name, comment in decrease_vars: clean_name = sanitize_enum_name(var_name).lower() header_content += f"\n/* Auto Create From Host Power Manager */\n" header_content += f"void rte_call_host_power_manager_decrease_variate{clean_name}active(uint32_t ulTimeMs);\n" # 为can任务添加CAN NM模块的rte_call接口声明(仅已启用的模块生成) if task == "can": for can_num, enable_nm, nm_module_name, nm_vars, nm_state_vars, nm_decrease_vars in can_nm_data_list: if enable_nm and (nm_state_vars or nm_decrease_vars): safe_module_name = re.sub(r'\^a-zA-Z0-9_', '', nm_module_name) if nm_state_vars: for var_name, comment in nm_state_vars: clean_name = sanitize_enum_name(var_name).lower() header_content += f"\n/* Auto Create From {nm_module_name} */\n" header_content += f"void rte_call{safe_module_name}state_variate{clean_name}active(void);\n" header_content += f"void rte_call{safe_module_name}state_variate{clean_name}deactive(void);\n" if nm_decrease_vars: for var_name, comment in nm_decrease_vars: clean_name = sanitize_enum_name(var_name).lower() header_content += f"\n/* Auto Create From {nm_module_name} */\n" header_content += f"void rte_call{safe_module_name}decrease_variate{clean_name}_active(uint32_t ulTimeMs);\n" header_content += f"\n#endif /* {task.upper()}_SW_H */\n" header_content = add_file_trailer(header_content, header_file_path) interface_comment = "/* 注意:所有软件组件对外的接口,必须在 sw.h 中声明,在 sw.c 中定义,\n" interface_comment += " * 接口类型必须是 runable, rte_call, rte_write, rte_read.\n" interface_comment += " *\n" interface_comment += " * 重要说明:本文件中的弱定义函数(xxx_user_impl)必须由用户重新定义。\n" interface_comment += " * 弱函数内部调用未定义符号 you_must_define_weak_impl,如不重定义将导致链接报错。\n" interface_comment += " * 这是设计行为,用于强制用户实现必要的业务逻辑。\n" interface_comment += " */\n\n" if os.path.exists(header_file_path): os.chmod(header_file_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(header_file_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(interface_comment) f.write(header_content) print(f"成功创建文件 '{header_file_path}'。") set_readonly(header_file_path) except Exception as e: handle_error_and_exit(f"创建文件 '{header_file_path}' 时发生错误:{e}") # 生成源文件 {task}swc.c source_file_path = os.path.join(task_dir, f"{task}swc.c") source_content = f"""#include "{task}swc.h" #include "../app_hook.h" #include "../../bsw/compiler_compat.h" #include "../../bsw/osif/osif.h" #include "../../bsw/osif/osif_task.h" #include "debug.h" #include <string.h> """ if task == "host" and enable_pm: source_content += '#include "power_manager.h"\n' # 为can任务添加CAN NM模块的头文件包含(仅已启用的模块) if task == "can": for can_num, enable_nm, nm_module_name, nm_vars, nm_state_vars, nm_decrease_vars in can_nm_data_list: if enable_nm and (nm_state_vars or nm_decrease_vars): safe_module_name = re.sub(r'\^a-zA-Z0-9_', '', nm_module_name) source_content += f'#include "{safe_module_name}.h"\n' # 收集所有需要生成弱定义函数的事件 weak_impl_decls = \[\] # 存储弱定义函数声明 source_content += "\n" source_content += "/*\n" source_content += " * 文件由工具生成,只读,不允许直接修改 !!!\n" source_content += " */\n\n" # 生成所有 user_impl / 接口函数的外部声明(仅声明,不生成函数体) source_content += f"/* Function declarations for {task} task */\n" source_content += "/* 用户可以在其他文件中重定义以下弱函数 (xxx_user_impl) 来实现自己的业务逻辑 */\n" source_content += "/* 注意:以下函数在 swc.c 中仅进行外部声明,具体实现由用户在其他文件中提供 */\n\n" # 初始化函数外部声明 source_content += f"extern void {task}init_user_impl(void);\n" # 如果有队列,生成队列创建后的外部声明(放在事件函数之前) if task in task_queues: msgs = task_queuestask source_content += "\n" source_content += "/* 队列句柄传递的弱定义函数,用户可重定义以获取队列句柄进行初始化操作 */\n" for msg_var, data_type, depth, comment in msgs: source_content += f"/*\n" source_content += f" * Demo: 在自己的代码中重定义此函数来使用队列句柄\n" source_content += f" * static osQueue_t *s{msg_var}handle; 放在函数外面\n" source_content += f" * void {task}{msg_var}handle_user_impl(osQueue_t *handle)\n" source_content += f" * {{\n" source_content += f" * s{msg_var}handle = handle; 保存队列句柄供后续使用\n" source_content += f" * }}\n" source_content += f" */\n" source_content += f"extern void {task}{msg_var}handle_user_impl(osQueue_t *handle);\n" for event in events: weak_impl_decls.append(f"{task}{event}user_impl") # 为特定事件添加详细注释 if event == "power_on": source_content += "/*\n" source_content += f" * {task}power_on_user_impl(void)\n" source_content += " * 设备上电或者复位启动,HOST任务首先检测供电电压,电压正常情况下,广播 power_on事件,\n" source_content += " * 收到该事件后任务执行开机流程,如打开一些外设电源\n" source_content += " */\n" elif event == "sleep": source_content += "/*\n" source_content += f" * {task}sleep_user_impl(void)\n" source_content += " * 系统满足休眠条件之后,HOST任务开始广播休眠请求,请求各个任务休眠,\n" source_content += " * 当前任务根据实际情况,需要确认当前业务都处理完了之后,依赖的任务休眠了才可以自我挂起,\n" source_content += " * OSIF_TaskSelfSuspendForIntoSleep 挂起的实现是一直等待wakeup事件,收到wakeup事件才退出\n" source_content += " *\n" source_content += " * DEMO1 演示,没有任务依赖,没有待处理的业务,直接挂起\n" source_content += f" * OSIF_TaskSelfSuspendForIntoSleep(TASK_ID{task.upper()});\n" source_content += " * DEMO2 演示,有任务依赖,或者有待处理的业务,不能立即挂起,需要在定时器事件,周期轮询判断,如\n" source_content += f" * {task}tick_5ms_runnable(void)\n" source_content += " * {\n" source_content += f" * if(OSIF_GetHostReqSlpFlag(TASK_ID{task.upper()}))\n" source_content += " * {\n" source_content += " * if(\n" source_content += " * 依赖的任务休眠了,相关业务处理完毕了\n" source_content += " * (OSIF_IsTaskSuspend(特定任务))&& (...)\n" source_content += " * )\n" source_content += f" * {{\n" source_content += f" * OSIF_TaskSelfSuspendForIntoSleep(TASK_ID{task.upper()});\n" source_content += " * }\n" source_content += " * }\n" source_content += " * }\n" source_content += " */\n" elif event == "wakeup": source_content += "/*\n" source_content += f" * {task}wakeup_user_impl(void)\n" source_content += " * 收到唤醒事件有两种情况,\n" source_content += " * 第一种情况是任务响应了休眠请求调用 执行了外设反初始化,关电源等操作,调用\n" source_content += " * OSIF_TaskSelfSuspendForIntoSleep挂起 ,这个状态下收到的wakup事件 唤醒,执行重新上电,初始化外设功能。\n" source_content += " * 第二种情况是任务收到了SELLP事件之后,因为任务有依赖,没有执行休眠确认,\n" source_content += " * 在此期间,有其他任务或者业务需求,要求中止休眠,要不要重新初始化外设,打开电源,业务上做判断处理。\n" source_content += " *\n" source_content += f" * if(OSIF_GetTaskSlpComfirmFlag(TASK_ID{task.upper()}))\n" source_content += " * {\n" source_content += " * 第一种情况:根据实际添加业务代码\n" source_content += " * }\n" source_content += " * else\n" source_content += " * {\n" source_content += " * 第二种情况:根据实际添加业务代码\n" source_content += " * }\n" source_content += " */\n" elif event == "task_queue": if task in task_queues and len(task_queuestask) > 0: source_content += "/*\n" source_content += f" * {task}task_queue_user_impl(void)\n" source_content += " * 消息队列处理 demo\n" source_content += " * (前提:已在 xxx_handle_user_impl 中将句柄保存到静态变量 s_xxx_handle)\n" for msg_var, data_type, depth, comment in task_queuestask: source_content += f" * {data_type} {msg_var}buf;\n" source_content += f" * while(OSIF_TaskQueueMsgGet(*s{msg_var}handle, &{msg_var}buf))\n" source_content += " * {\n" source_content += " * 添加业务逻辑代码\n" source_content += " * 处理接收到的消息数据\n" source_content += " * }\n" source_content += " *\n" source_content += " * 消息处理需要特别耗时或存在前置依赖条件时,建议转移到特定定时事件中轮询处理\n" source_content += f" * 可在 {task}tick_5ms_runnable 事件中实现\n" source_content += " * 注意:在定时事件中应使用 if 而非 while,原因如下:\n" source_content += " * - while 会一次性处理所有消息,可能导致该周期超时\n" source_content += " * - if 每次只处理一条,剩余消息在下次调度时继续处理\n" source_content += " * - 这样可以保证调度周期的准确性,不影响其他任务\n" source_content += " */\n" source_content += f"extern void {task}{event}user_impl(void);\n" # 生成 CS 接口外部声明(放在事件函数之后) if task in interface_functions: source_content += "\n" source_content += "/* CS 接口弱定义函数,用户可重定义以实现接口调用逻辑 */\n" for decl, desc in interface_functionstask: # 解析函数签名 decl_stripped = decl.rstrip(';').strip() # 提取函数名 func_name = "" if "rte_call" in decl_stripped: match = re.search(r'rte_call\w+', decl_stripped) if match: func_name = match.group() else: func_name = decl_stripped.split('(')0.strip().split()-1 else: func_name = decl_stripped.split('(')0.strip().split()-1 # 添加详细注释到弱函数定义前 if desc: source_content += "/*\n" source_content += f" * {func_name}\n" source_content += f" * {desc}\n" source_content += " */\n" # 生成外部声明 source_content += f"extern {decl_stripped};\n" source_content += "\n" source_content += "\n" if task in sr_variables: print(f"任务 '{task}' 的 SR 变量检查: {'有' if task in sr_variables else '无'}") print(f" 任务 '{task}' 有 {len(sr_variablestask)} 个 SR 变量,将生成代码。") source_content += "/* SR Port Interface Variables */\n" for var_name, var_type, comment in sr_variablestask: if comment: source_content += f"/*********** {comment} **********/\n" source_content += f"static {var_type} s{var_name};\n\n" source_content += "\n/* SR Port Interface Functions */\n" for var_name, var_type, comment in sr_variablestask: if comment: source_content += f"/************** {comment} ********* */\n" source_content += f"""void rte_write{var_name}({var_type}* param) {{ uint32_t saveVar = 0; OSIF_UNIFIED_ENTER_CRITICAL(saveVar); memcpy(&s{var_name}, param, sizeof({var_type})); OSIF_UNIFIED_EXIT_CRITICAL(saveVar); }} """ source_content += f"""void rte_read{var_name}({var_type} *param) {{ uint32_t saveVar = 0; OSIF_UNIFIED_ENTER_CRITICAL(saveVar); memcpy(param, &s{var_name}, sizeof({var_type})); OSIF_UNIFIED_EXIT_CRITICAL(saveVar); }} """ source_content += "\n" if task in task_queues: msgs = task_queuestask source_content += "/* Task Queue Variables */\n" for msg_var, data_type, depth, comment in msgs: if comment: source_content += f"/*********** {comment} **********/\n" source_content += f"static osQueue_t {msg_var};\n" # 静态队列存储区定义(大小 = 队列长度 * 项目大小) source_content += f"static uint8_t {msg_var}storage{depth} \* sizeof({data_type});\n" source_content += f"static StaticQueue_t {msg_var}struct;\n\n" source_content += "/* Task Queue Creation Function (Static) */\n" source_content += f"void rte_call{task}queue_create(void)\n" source_content += "{\n" for msg_var, data_type, depth, comment in msgs: source_content += f" {msg_var} = OSIF_QueueCreateStatic({depth}, sizeof({data_type}), {msg_var}storage, &{msg_var}struct);\n" source_content += f" {task}{msg_var}handle_user_impl(&{msg_var}); /* 调用弱定义函数,传递队列句柄指针 */\n" source_content += "}\n\n" # 添加发送函数定义 source_content += "/* Task Queue Send Functions */\n" for msg_var, data_type, depth, comment in msgs: source_content += f"uint8_t rte_call_send{task}{msg_var}({data_type} *pQItem)\n" source_content += "{\n" source_content += f" return OSIF_TaskQueueMsgSend(TASK_ID{task.upper()}, {msg_var}, pQItem);\n" source_content += "}\n\n" source_content += f"/* Initialization function */\n" source_content += f"void {task}init_runnable(void)\n" source_content += "{\n" source_content += f" {task}init_user_impl(); /* 调用用户可重定义的弱函数 */\n" source_content += "}\n\n" source_content += f"/* Event send function */\n" source_content += f"void rte_call_send{task}task_event({task_camel}Evt_E e{task_camel}Evt)\n" source_content += "{\n" source_content += f" OSIF_TaskEventSend(TASK_ID{task.upper()}, e{task_camel}Evt);\n" source_content += "}\n\n" source_content += "\n\n" # 生成实际的 runnable 函数,调用弱定义函数 for event in events: if event.upper() in common_suffixes: hook = f" {event.upper()}RUNNABLE_HOOK(TASK_ID{task.upper()});" else: hook = "" source_content += f"void {task}{event}runnable(void)\n" source_content += "{\n" if hook: source_content += hook + "\n" if event == "soft_wdt": source_content += f" OSIF_TaskSoftWdtFeed(TASK_ID{task.upper()});\n" source_content += f" {task}{event}user_impl(); /* 调用用户可重定义的弱函数,详细说明见弱函数定义处 */\n" source_content += "}\n\n" if task == "host" and enable_pm: if state_vars: for var_name, comment in state_vars: clean_name = sanitize_enum_name(var_name).lower() source_content += "/* Auto Create From Host Power Manager */\n" source_content += f"void rte_call_host_power_manager_state_variate{clean_name}active(void)\n" source_content += "{\n" source_content += f" power_manager_state_variate{clean_name}active();\n" source_content += "}\n\n" source_content += "/* Auto Create From Host Power Manager */\n" source_content += f"void rte_call_host_power_manager_state_variate{clean_name}deactive(void)\n" source_content += "{\n" source_content += f" power_manager_state_variate{clean_name}deactive();\n" source_content += "}\n\n" if decrease_vars: for var_name, comment in decrease_vars: clean_name = sanitize_enum_name(var_name).lower() source_content += "/* Auto Create From Host Power Manager */\n" source_content += f"void rte_call_host_power_manager_decrease_variate{clean_name}active(uint32_t ulTimeMs)\n" source_content += "{\n" source_content += f" power_manager_decrease_variate{clean_name}active(ulTimeMs);\n" source_content += "}\n\n" # 为can任务添加CAN NM模块的rte_call接口函数定义(仅已启用的模块) if task == "can": for can_num, enable_nm, nm_module_name, nm_vars, nm_state_vars, nm_decrease_vars in can_nm_data_list: if enable_nm and (nm_state_vars or nm_decrease_vars): safe_module_name = re.sub(r'\^a-zA-Z0-9_', '', nm_module_name) if nm_state_vars: for var_name, comment in nm_state_vars: clean_name = sanitize_enum_name(var_name).lower() source_content += f"/* Auto Create From {nm_module_name} */\n" source_content += f"void rte_call{safe_module_name}state_variate{clean_name}_active(void)\n" source_content += "{\n" source_content += f" {safe_module_name}state_variate{clean_name}active();\n" source_content += "}\n\n" source_content += f"/* Auto Create From {nm_module_name} */\n" source_content += f"void rte_call{safe_module_name}state_variate{clean_name}_deactive(void)\n" source_content += "{\n" source_content += f" {safe_module_name}state_variate{clean_name}deactive();\n" source_content += "}\n\n" if nm_decrease_vars: for var_name, comment in nm_decrease_vars: clean_name = sanitize_enum_name(var_name).lower() source_content += f"/* Auto Create From {nm_module_name} */\n" source_content += f"void rte_call{safe_module_name}decrease_variate{clean_name}_active(uint32_t ulTimeMs)\n" source_content += "{\n" source_content += f" {safe_module_name}decrease_variate{clean_name}_active(ulTimeMs);\n" source_content += "}\n\n" source_content = add_file_trailer(source_content, source_file_path) if os.path.exists(source_file_path): os.chmod(source_file_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(source_file_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(interface_comment) f.write(source_content) print(f"成功创建文件 '{source_file_path}'。") set_readonly(source_file_path) except Exception as e: handle_error_and_exit(f"创建文件 '{source_file_path}' 时发生错误:{e}") | |
| 30 | compiler_compat.h || app_compiler_compat_h_path = os.path.join(bsw_dir, "compiler_compat.h") weak_def_content = """#ifndef COMPILER_COMPAT_H #define COMPILER_COMPAT_H /* * 编译器兼容宏定义,支持弱定义、对齐等跨编译器特性 * 用户可在其他文件中重定义这些弱函数,实现自己的业务逻辑 */ /* Compiler Detection for Weak Attribute */ #if defined(__CC_ARM) || defined(__ARMCLANG_VERSION) /* Keil MDK-ARM / ARM Compiler 5 & 6 */ #define COMPAT_WEAK_DEF attribute((weak)) #define COMPAT_UNUSED attribute((unused)) #elif defined(ICCARM) /* IAR Compiler */ #define COMPAT_WEAK_DEF __weak #define COMPAT_UNUSED attribute((unused)) #elif defined(TI_COMPILER) /* TI Compiler */ #define COMPAT_WEAK_DEF __weak #define COMPAT_UNUSED #elif defined(GNUC) /* ARM GCC / GNU Compiler */ #define COMPAT_WEAK_DEF attribute((weak)) #define COMPAT_UNUSED attribute((unused)) #else #define COMPAT_WEAK_DEF #define COMPAT_UNUSED #endif #endif /* COMPILER_COMPAT_H */ """ weak_def_content = add_file_trailer(weak_def_content, app_compiler_compat_h_path) if os.path.exists(app_compiler_compat_h_path): os.chmod(app_compiler_compat_h_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(app_compiler_compat_h_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(weak_def_content) print(f"成功创建文件 '{app_compiler_compat_h_path}'。") set_readonly(app_compiler_compat_h_path) except Exception as e: handle_error_and_exit(f"创建文件 '{app_compiler_compat_h_path}' 时发生错误:{e}") | |
| 31 | app_hook.h app_hook.c || app_hook_h_path = os.path.join(app_dir, "app_hook.h") app_hook_c_path = os.path.join(app_dir, "app_hook.c") hook_h_lines = \[\] hook_h_lines.append("#ifndef APP_HOOK_H") hook_h_lines.append("#define APP_HOOK_H") hook_h_lines.append("") hook_h_lines.append("#include \"../bsw/osif/osif_task_cfg.h\" // for TaskID_E") hook_h_lines.append("") en_lines = \[\] for suffix in common_suffixes: en_lines.append(f"#define {suffix}_RUNNABLE_HOOK_EN 0") hook_h_lines.extend(en_lines) if en_lines: hook_h_lines.append("") hook_h_lines.append("/* Hook function declarations */") if common_suffixes: for suffix in common_suffixes: func_name = f"{suffix.lower()}_runnable_hook" hook_h_lines.append(f"void {func_name}(TaskID_E eTaskID);") hook_h_lines.append("") else: hook_h_lines.append("/* No hook functions defined */") hook_h_lines.append("") for i, suffix in enumerate(common_suffixes): macro = f"{suffix}_RUNNABLE_HOOK" func_name = f"{suffix.lower()}_runnable_hook" hook_h_lines.append(f"#if ({macro}_EN)") hook_h_lines.append(f"#define {macro}(eTaskID) {func_name}(eTaskID)") hook_h_lines.append("#else") hook_h_lines.append(f"#define {macro}(eTaskID) ") hook_h_lines.append("#endif") if i < len(common_suffixes) - 1: hook_h_lines.append("") hook_h_lines.append("") hook_h_lines.append("#endif /* APP_HOOK_H */") hook_h_content = "\n".join(hook_h_lines) hook_h_content = add_file_trailer(hook_h_content, app_hook_h_path) hook_c_lines = \[\] hook_c_lines.append("#include \"app_hook.h\"") hook_c_lines.append("#include \"../bsw/osif/osif.h\"") hook_c_lines.append("#include \"../bsw/osif/osif_task.h\"") hook_c_lines.append("#include \"debug.h\"") hook_c_lines.append("") for suffix in common_suffixes: func_name = f"{suffix.lower()}runnable_hook" hook_c_lines.append(f"void {func_name}(TaskID_E eTaskID)") hook_c_lines.append("{") hook_c_lines.append(f" LOG_DEBUG(\"%s %s\\r\\n\", OSIF_TaskGetName(eTaskID), \"{suffix}\");") hook_c_lines.append(" /* add your hook code here */") hook_c_lines.append("}") hook_c_lines.append("") hook_c_content = "\n".join(hook_c_lines) hook_c_content = add_file_trailer(hook_c_content, app_hook_c_path) if os.path.exists(app_hook_h_path): os.chmod(app_hook_h_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(app_hook_h_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(hook_h_content) print(f"成功创建文件 '{app_hook_h_path}'。") set_readonly(app_hook_h_path) except Exception as e: handle_error_and_exit(f"创建文件 '{app_hook_h_path}' 时发生错误:{e}") if os.path.exists(app_hook_c_path): os.chmod(app_hook_c_path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: with open(app_hook_c_path, 'w', encoding='utf-8') as f: f.write(readonly_comment) f.write(hook_c_content) print(f"成功创建文件 '{app_hook_c_path}'。") set_readonly(app_hook_c_path) except Exception as e: handle_error_and_exit(f"创建文件 '{app_hook_c_path}' 时发生错误:{e}") print("\n所有数据:") print(df.to_string()) show_success_message() | |
| 32 | 函数 || def show_error_message(message): """显示错误消息:优先使用弹框,否则打印带边框的醒目文本""" if TK_AVAILABLE: root = tk.Tk() root.withdraw() messagebox.showerror("错误", message) root.destroy() else: border = "=" * 60 print(f"\n{border}") print(f"错误: {message}") print(f"{border}\n") def cleanup_output(): """尝试删除 output 目录(如果存在),忽略删除错误""" if os.path.exists(BASE_DIR): try: print(f"检测到错误,正在清理目录 '{BASE_DIR}'...") remove_readonly(BASE_DIR) shutil.rmtree(BASE_DIR) print(f"目录 '{BASE_DIR}' 已删除。") except Exception as e: print(f"警告:清理目录 '{BASE_DIR}' 时发生错误:{e}") def handle_error_and_exit(message): """显示错误信息、清理输出目录、退出脚本""" show_error_message(message) cleanup_output() sys.exit(1) def show_success_message(): """脚本正常结束时显示成功消息""" border = "=" * 60 print(f"\n{border}") print("所有文件生成成功!") print(f"生成的文件位于 {BASE_DIR}/ 目录下。") print(f"{border}\n") def sanitize_enum_name(name): """将任意字符串转换为合法的C枚举标识符:字母数字下划线,且不以数字开头""" s = re.sub(r'\W+', '', str(name)) return s def capitalize_first(s): """将字符串首字母大写,其余保持不变""" if not s: return s return s0.upper() + s1: def get_file_md5(filepath): """计算文件的MD5哈希值""" hash_md5 = hashlib.md5() with open(filepath, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def set_readonly(filepath): """将文件设置为只读(所有用户只读)""" try: os.chmod(filepath, stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH) # 0o444 print(f"已设置只读: {filepath}") except Exception as e: print(f"设置只读失败 {filepath}: {e}") def remove_readonly(path): """递归移除目录下所有文件的只读属性(设为可读写)""" if os.path.isfile(path): os.chmod(path, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) elif os.path.isdir(path): for root, dirs, files in os.walk(path): for file in files: filepath = os.path.join(root, file) os.chmod(filepath, stat.S_IWRITE | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) def add_file_trailer(content, filepath): """根据文件类型在内容末尾添加尾部(空行或结束注释)""" ext = os.path.splitext(filepath)1 if ext == '.c': return content + "\n/* End of file */\n" elif ext in '.h', '.txt': return content + "\n" else: return content def copy_util_files(src_util_dir, dst_dir, header_comment): """将源目录下所有 .c 和 .h 文件复制到目标目录,并在文件头部插入注释头,然后设置为只读""" if not os.path.isdir(src_util_dir): print(f"警告:源目录 '{src_util_dir}' 不存在,跳过文件拷贝。") return files = glob.glob(os.path.join(src_util_dir, "*.c")) + glob.glob(os.path.join(src_util_dir, "*.h")) if not files: print(f"警告:源目录 '{src_util_dir}' 中没有找到 .c 或 .h 文件。") return for file in files: try: dst_file = os.path.join(dst_dir, os.path.basename(file)) shutil.copy2(file, dst_file) print(f"已复制: {file} -> {dst_file}") with open(dst_file, 'r', encoding='utf-8') as f: original_content = f.read() new_content = header_comment + original_content new_content = add_file_trailer(new_content, dst_file) with open(dst_file, 'w', encoding='utf-8') as f: f.write(new_content) print(f"已为文件 '{dst_file}' 添加头部注释和尾部。") set_readonly(dst_file) except Exception as e: print(f"处理文件 {file} 时出错:{e}") | |
autosar 架构脚本提示语
SuperByteMaster2026-08-14 14:21
相关推荐
Zane19941 小时前
钻石继承调用哪个方法?一文讲透 MRO 与 C3 线性化算法kevinnett1 小时前
图片生成跑到一半“失踪”了:我重新设计了异步任务状态机小白勇闯网安圈1 小时前
Django 模板复用、ORM 查询与多对多关系TheBestRucy1 小时前
基于Dify的旅游攻略&王者荣耀攻略智能助手项目天才少女爱迪生2 小时前
KIMI-K3技术博客写作思路分析丨白色风车丨2 小时前
MCP 入门指南:大模型时代的“USB-C”接口EXI-小洲2 小时前
Web Spider 某渣渣企业平台 表单参数逆向 Webpack玫幽倩3 小时前
2026聚合獬豸杯决赛wp(手机取证)FlyWIHTSKY3 小时前
在智能体系统中,什么是多模态,举例详细说明