From 1e774185043f8dd880034484b61415ded67b4ece Mon Sep 17 00:00:00 2001 From: ebrother Date: Tue, 27 Oct 2026 23:14:07 +0800 Subject: [PATCH] initial version --- CommCfg.json | 1 + Main.c | 3 + VarTable.csv | 2 + code_generator.py | 328 ++++++++++++++++++++++++++++++++++++++++++++++ prompts.md | 15 +++ 5 files changed, 349 insertions(+) create mode 100644 CommCfg.json create mode 100644 VarTable.csv create mode 100644 code_generator.py create mode 100644 prompts.md diff --git a/CommCfg.json b/CommCfg.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/CommCfg.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/Main.c b/Main.c index 4c07eeb..e89e259 100644 --- a/Main.c +++ b/Main.c @@ -3,6 +3,9 @@ void init(void) { } + void loop(void) { + VR[WORD(200)] = VR[WORD(300)] * 0.1; // var1 + VR[WORD(202)] = VR[WORD(302)] * 0.01; // var2 } diff --git a/VarTable.csv b/VarTable.csv new file mode 100644 index 0000000..e4f187a --- /dev/null +++ b/VarTable.csv @@ -0,0 +1,2 @@ +var1,V,F32,WORD,200,0.1 +var2,V,F32,WORD,202,0.01 diff --git a/code_generator.py b/code_generator.py new file mode 100644 index 0000000..7bb9996 --- /dev/null +++ b/code_generator.py @@ -0,0 +1,328 @@ +# -*- coding: utf-8 -*- +""" +变量表 -> C 程序 代码生成工具 + +功能: + 1. 选择变量表 CSV 文件(BlockWare 变量表格式)。 + 2. 输入一个地址偏移量。 + 3. 输入数据更新周期(单位:秒,默认 10),控制多久计算一次。 + 4. 点击“生成”按钮后,生成 Main.c: + - 每到一个更新周期,对每一行变量,把「地址 + 地址偏移」处的数据, + 乘以「备注」列里的数值,结果写回「地址」处。 + - 如果「备注」为空,则跳过该行。 + +变量表 CSV 格式(逗号分隔,第 6 列是备注,可省略): + 变量名,存储区,数据类型,寻址方式,地址,备注 + 例如:var1,V,F32,WORD,200,0.1 + +用法: + python code_generator.py +""" + +import csv +import os + +try: + import tkinter as tk + from tkinter import ttk, filedialog, messagebox + from tkinter import scrolledtext + _HAS_TK = True +except ImportError: # pragma: no cover - 某些精简环境可能没有 tkinter + _HAS_TK = False + + +# 数据类型缩写 -> C 语言类型字母(放在存储区之后,构成 VR/VW/VD 等) +TYPE_LETTER = { + "BOOL": "", # 布尔值,无类型字母,如 V[BIT(0)] / V[WORD(0.1)]#AB + "U8": "B", + "S16": "S", + "U16": "W", + "S32": "I", + "U32": "D", + "S64": "LI", + "U64": "LD", + "F32": "R", + "F64": "LR", +} + +# 合法的数据存储区 +VALID_AREAS = {"V", "L", "M", "I", "Q", "E", "F"} + + +def parse_type(type_str): + """解析数据类型列,返回 (基础类型大写, 字节序或None)。 + + 例如 "F32" -> ("F32", None) + "U32#CDAB" -> ("U32", "CDAB") + """ + type_str = type_str.strip() + if "#" in type_str: + base, byte_order = type_str.split("#", 1) + return base.strip().upper(), byte_order.strip() + return type_str.upper(), None + + +def type_expr(area, type_str, addressing, address): + """根据存储区/数据类型/寻址方式/地址构造 C 语言寻址表达式。 + + 例如 ("V", "F32", "WORD", "200") -> "VR[WORD(200)]" + ("V", "U32#CDAB", "WORD", "200") -> "VD[WORD(200)]#CDAB" + 返回 None 表示数据类型不支持。 + """ + base, byte_order = parse_type(type_str) + letter = TYPE_LETTER.get(base) + if letter is None: + return None + expr = "%s%s[%s(%s)]" % (area.upper(), letter, addressing.upper(), address) + if byte_order: + expr += "#" + byte_order + return expr + + +def add_offset(address, offset): + """给地址加上偏移量。地址可能带位/字节内偏移,如 "100.12"。 + + 偏移只作用在整数部分。 + """ + address = str(address).strip() + if offset == 0: + return address + if "." in address: + int_part, frac = address.split(".", 1) + return "%d.%s" % (int(int_part) + offset, frac) + return str(int(address) + offset) + + +def seconds_to_ms(seconds): + """把数据更新周期(秒)换算成毫秒,并做合法性校验。""" + seconds = float(seconds) + ms = int(round(seconds * 1000)) + if ms <= 0: + raise ValueError("数据更新周期必须大于 0 秒。") + if ms > 86400000: + raise ValueError("数据更新周期不能超过 86400 秒(1 天)。") + return ms + + +def generate_c(csv_path, offset, period_seconds=10): + """读取变量表,生成 Main.c 的内容。 + + 参数 period_seconds 为数据更新周期(单位秒)。 + + 返回 (c_code, skipped),其中 skipped 是 [(行信息, 原因), ...]。 + """ + offset = int(offset) + statements = [] + skipped = [] + + with open(csv_path, "r", encoding="utf-8-sig", newline="") as f: + reader = csv.reader(f) + for row in reader: + # 去掉空行 + if not row or all(not c.strip() for c in row): + continue + + # 列数不足 5 列,无法构成有效变量,跳过 + if len(row) < 5: + skipped.append((",".join(row), "列数不足")) + continue + + name = row[0].strip() + area = row[1].strip().upper() + type_str = row[2].strip() + addressing = row[3].strip() + address = row[4].strip() + remark = row[5].strip() if len(row) > 5 else "" + + # 存储区不是合法区域时,当作表头/说明行跳过 + if area not in VALID_AREAS: + continue + + # 备注为空,跳过不处理 + if not remark: + continue + + # 备注必须是数值 + try: + float(remark) + except ValueError: + skipped.append((name, "备注不是数值: %s" % remark)) + continue + + # 地址必须是整数(数值型变量正常都是纯整数地址) + try: + int(address.split(".")[0]) + except ValueError: + skipped.append((name, "地址不是数值: %s" % address)) + continue + + dest = type_expr(area, type_str, addressing, address) + src = type_expr(area, type_str, addressing, + add_offset(address, offset)) + if dest is None or src is None: + skipped.append((name, "不支持的数据类型: %s" % type_str)) + continue + + comment = (" // %s" % name) if name else "" + statements.append("%s = %s * %s;%s" % (dest, src, remark, comment)) + + c_code = build_main_c(statements, seconds_to_ms(period_seconds)) + return c_code, skipped + + +def build_main_c(statements, period_ms): + """用标准程序框架包裹生成的计算语句,并按更新周期定时执行。""" + lines = ['#include "sys.h"', "", "void init(void)", "{", "}", "", "void loop(void)", "{"] + if statements: + lines.append(" /* 每 %d 毫秒计算一次 */" % period_ms) + lines.append(" if (sysTON(0, 1, %d))" % period_ms) + lines.append(" {") + for s in statements: + lines.append(" " + s) + lines.append(" sysTRst(0);") + lines.append(" }") + else: + lines.append(" /* 没有需要计算的变量 */") + lines.append("}") + lines.append("") + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# GUI +# --------------------------------------------------------------------------- +class App(object): + def __init__(self, root): + self.root = root + root.title("变量表 -> Main.c 生成工具") + root.resizable(True, True) + + frame = ttk.Frame(root, padding=12) + frame.pack(fill="both", expand=True) + frame.columnconfigure(1, weight=1) + + # 地址偏移 + ttk.Label(frame, text="地址偏移:").grid( + row=0, column=0, sticky="w", pady=4) + self.offset_var = tk.StringVar(value="0") + self.offset_entry = ttk.Entry(frame, textvariable=self.offset_var, width=16) + self.offset_entry.grid(row=0, column=1, sticky="w", pady=4) + + # 数据更新周期(秒) + ttk.Label(frame, text="数据更新周期(秒):").grid( + row=1, column=0, sticky="w", pady=4) + self.period_var = tk.StringVar(value="10") + self.period_entry = ttk.Entry(frame, textvariable=self.period_var, width=16) + self.period_entry.grid(row=1, column=1, sticky="w", pady=4) + + # 文件选择 + ttk.Label(frame, text="变量表文件:").grid( + row=2, column=0, sticky="w", pady=4) + self.file_var = tk.StringVar() + # 默认预填当前目录下的 VarTable.csv + default_csv = os.path.join(os.getcwd(), "VarTable.csv") + if os.path.isfile(default_csv): + self.file_var.set(default_csv) + self.file_entry = ttk.Entry(frame, textvariable=self.file_var) + self.file_entry.grid(row=2, column=1, sticky="ew", pady=4) + ttk.Button(frame, text="浏览...", command=self.browse).grid( + row=2, column=2, padx=(6, 0)) + + # 生成按钮 + self.gen_btn = ttk.Button(frame, text="生成 Main.c", command=self.generate) + self.gen_btn.grid(row=3, column=0, columnspan=3, sticky="ew", pady=8) + + # 日志输出区 + self.log = scrolledtext.ScrolledText(frame, height=14, width=70, state="disabled") + self.log.grid(row=4, column=0, columnspan=3, sticky="nsew") + frame.rowconfigure(4, weight=1) + + def log_msg(self, text): + self.log.configure(state="normal") + self.log.insert("end", text + "\n") + self.log.see("end") + self.log.configure(state="disabled") + + def clear_log(self): + self.log.configure(state="normal") + self.log.delete("1.0", "end") + self.log.configure(state="disabled") + + def browse(self): + path = filedialog.askopenfilename( + title="选择变量表 CSV 文件", + filetypes=[("CSV 文件", "*.csv"), ("所有文件", "*.*")], + ) + if path: + self.file_var.set(path) + + def generate(self): + csv_path = self.file_var.get().strip() + if not csv_path: + messagebox.showwarning("提示", "请先选择变量表 CSV 文件。") + return + if not os.path.isfile(csv_path): + messagebox.showerror("错误", "文件不存在:\n%s" % csv_path) + return + + offset_text = self.offset_var.get().strip() + if offset_text == "": + offset_text = "0" + try: + offset = int(offset_text) + except ValueError: + messagebox.showerror("错误", "地址偏移必须是整数。") + return + + period_text = self.period_var.get().strip() + if period_text == "": + period_text = "10" + try: + period_ms = seconds_to_ms(period_text) + except ValueError as exc: + messagebox.showerror("错误", str(exc)) + return + + self.clear_log() + try: + c_code, skipped = generate_c(csv_path, offset, period_text) + except Exception as exc: # 捕获解析错误并提示 + messagebox.showerror("错误", "生成失败:\n%s" % exc) + return + + out_dir = os.path.dirname(os.path.abspath(csv_path)) + out_path = os.path.join(out_dir, "Main.c") + with open(out_path, "w", encoding="utf-8", newline="\n") as f: + f.write(c_code) + + self.log_msg("已生成: %s" % out_path) + self.log_msg("地址偏移: %d" % offset) + self.log_msg("数据更新周期: %d 毫秒" % period_ms) + self.log_msg("源变量表: %s" % csv_path) + self.log_msg("-" * 40) + self.log_msg(c_code.rstrip()) + self.log_msg("-" * 40) + if skipped: + self.log_msg("跳过 %d 行:" % len(skipped)) + for name, reason in skipped: + self.log_msg(" - %s: %s" % (name, reason)) + else: + self.log_msg("处理完成,没有跳过的行。") + + messagebox.showinfo("完成", "已生成:\n%s" % out_path) + + +def main(): + if not _HAS_TK: + print("当前环境未安装 tkinter,无法启动图形界面。") + print("请安装:pip install tk 或在系统中启用 Tk。") + return 1 + root = tk.Tk() + App(root) + root.mainloop() + return 0 + + +if __name__ == "__main__": + import sys + sys.exit(main()) diff --git a/prompts.md b/prompts.md new file mode 100644 index 0000000..2636374 --- /dev/null +++ b/prompts.md @@ -0,0 +1,15 @@ +# 说明 +- 使用python做个带界面的工具包含如下功能 + - 界面包含 + - 地址偏移输入框 + - 数据更新周期输入框(单位秒),默认10 + - 设定多久计算一次(不需要很频繁计算) + - 文件选择框 + - 计算处理 + - 文件是csv文件,也就是变量表 + - 当点击生成按钮的时候,生成C程序,文件名为Main.c,该程序实现 + - 把"地址+地址偏移"的数据类型乘以备注里面的数值,结果存到"地址"里面 + - 如果备注为空,则跳过不处理 + +# 参考 +- http://www.brimesh.com/blockware_spec/v3/cn