feat(cp02): add build GUI, flash guide, and comment removal tool

Add build_gui.html for visual command generation, flash_guide.md for
flashing reference, and remove_chinese_comments.py for cleaning source
files. Update extract_firmware.sh to use output directory instead of
prefix, and update README with all new tools.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Ching L 2026-02-26 13:57:52 +08:00
parent e5a9369440
commit 6ad3ab93a7
5 changed files with 784 additions and 24 deletions

View File

@ -21,12 +21,13 @@
### extract_firmware.sh ### extract_firmware.sh
- **功能**: 从合并的 bin 文件中提取 firmware、IUM 和 metadata - **功能**: 从合并的 bin 文件中提取 firmware、IUM 和 metadata
- **用法**: `./extract_firmware.sh <merged_bin> [output_prefix]` - **用法**: `./extract_firmware.sh <merged_bin> [output_dir]`
- **描述**: - **描述**:
- 从固定偏移位置提取 firmware (0x04000) - 从固定偏移位置提取 firmware (0x04000)
- 提取 IUM 数据 (0x1dc00, 256 bytes) - 提取 IUM 数据 (0x1dc00, 256 bytes)
- 解析并生成 metadata.json (blocks 和 last_block_size) - 解析并生成 metadata.json (blocks 和 last_block_size)
- 如未指定前缀,自动使用原文件名 - 如未指定输出目录,默认输出到当前目录
- 自动创建不存在的输出目录
### get_last_bytes.sh ### get_last_bytes.sh
- **功能**: 获取 IUM 文件的最后两个字节并以十六进制格式返回 - **功能**: 获取 IUM 文件的最后两个字节并以十六进制格式返回
@ -99,6 +100,31 @@
- 自动处理重名文件(添加 _1, _2 等后缀) - 自动处理重名文件(添加 _1, _2 等后缀)
- 显示复制进度和统计信息 - 显示复制进度和统计信息
### remove_chinese_comments.py
- **功能**: 从源代码文件中移除中文注释
- **用法**: `python3 remove_chinese_comments.py [--check] <file> [file2 ...]`
- **描述**:
- 支持 C/C++`//` 注释)和 Python`#` 注释)文件
- 整行中文注释直接删除,行尾中文注释只移除注释部分
- `--check` 模式仅显示中文注释,不做修改
- 交互式确认后才执行删除
### build_gui.html
- **功能**: IonBridge 构建工具的可视化命令生成器
- **用法**: 在浏览器中打开 `build_gui.html`
- **描述**:
- 支持选择 variantCP02、CP02S、3536、GPU Demo、Bird
- 可配置 build 选项production、coredump和 flash 选项littlefs、protected_data、nvs 等)
- 一键生成 Build、Flash、Monitor、Clean 等命令并复制
- 自动保存配置和命令历史到 localStorage
### flash_guide.md
- **功能**: IonBridge 烧录操作参考文档
- **描述**:
- 非 Secure 设备(开发板)的 build/flash/monitor 命令示例
- Secure 设备(量产板)的签名烧录流程
- sign_key 和 psn 参数说明
### merge_encrypted_firmware.py ### merge_encrypted_firmware.py
- **功能**: 合成已加密的固件和 IUM 为最终 programmer 固件 - **功能**: 合成已加密的固件和 IUM 为最终 programmer 固件
- **用法**: `python3 merge_encrypted_firmware.py <base.bin> <encrypted.bin> <ium.bin> -o <output.bin>` - **用法**: `python3 merge_encrypted_firmware.py <base.bin> <encrypted.bin> <ium.bin> -o <output.bin>`
@ -123,8 +149,8 @@
./merge_2323_firmware.sh -u PA768_Updater.bin -f 2323_firmware.bin -i 2323_ium.bin -o merged.bin ./merge_2323_firmware.sh -u PA768_Updater.bin -f 2323_firmware.bin -i 2323_ium.bin -o merged.bin
# 提取固件组件 # 提取固件组件
./extract_firmware.sh 40_ufcs2.bin firmware # 指定输出前缀 ./extract_firmware.sh 40_ufcs2.bin /tmp/output # 输出到指定目录
./extract_firmware.sh merged.bin # 使用原文件名作为前缀 ./extract_firmware.sh merged.bin # 输出到当前目录
# 获取 IUM 文件的最后两个字节 # 获取 IUM 文件的最后两个字节
./get_last_bytes.sh ium.bin # 使用默认文件 ./get_last_bytes.sh ium.bin # 使用默认文件
@ -151,4 +177,8 @@ python3 merge_encrypted_firmware.py base.bin encrypted.bin ium.bin -o programmer
# 复制 .o 文件 # 复制 .o 文件
./copy_o_files.sh /path/to/build /path/to/output ./copy_o_files.sh /path/to/build /path/to/output
# 移除中文注释
python3 remove_chinese_comments.py --check main.c # 仅检查
python3 remove_chinese_comments.py main.c utils.py # 交互式移除
``` ```

546
CP02/build_gui.html Normal file
View File

@ -0,0 +1,546 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IonBridge Build Tool</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
:root {
--bg: #1a1b26;
--surface: #24283b;
--surface-hover: #2f3349;
--border: #3b4261;
--text: #c0caf5;
--text-dim: #565f89;
--accent: #7aa2f7;
--accent-hover: #89b4fa;
--green: #9ece6a;
--red: #f7768e;
--orange: #ff9e64;
--cyan: #7dcfff;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif;
background: var(--bg);
color: var(--text);
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.header {
padding: 14px 24px;
background: var(--surface);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.header h1 { font-size: 17px; font-weight: 600; color: var(--accent); }
.main { display: flex; flex: 1; overflow: hidden; }
.sidebar {
width: 300px;
background: var(--surface);
border-right: 1px solid var(--border);
padding: 16px;
overflow-y: auto;
flex-shrink: 0;
}
.section { margin-bottom: 20px; }
.section-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.8px;
color: var(--text-dim);
margin-bottom: 10px;
}
label.field-label {
display: block;
font-size: 12px;
color: var(--text-dim);
margin-bottom: 4px;
}
select, input[type="text"] {
width: 100%;
padding: 7px 10px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
font-size: 13px;
outline: none;
margin-bottom: 10px;
}
select:focus, input:focus { border-color: var(--accent); }
.checkbox-group { display: flex; flex-wrap: wrap; gap: 6px; }
.checkbox-item {
display: flex;
align-items: center;
gap: 5px;
padding: 5px 9px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
cursor: pointer;
font-size: 12px;
transition: all 0.15s;
user-select: none;
}
.checkbox-item:hover { border-color: var(--accent); }
.checkbox-item input[type="checkbox"] { accent-color: var(--accent); width: 14px; height: 14px; }
.checkbox-item.checked {
border-color: var(--accent);
background: rgba(122, 162, 247, 0.08);
}
.actions { display: flex; flex-direction: column; gap: 6px; }
.btn {
padding: 9px 14px;
border: none;
border-radius: 7px;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.btn-primary { background: var(--accent); color: var(--bg); }
.btn-primary:hover { background: var(--accent-hover); }
.btn-green { background: var(--green); color: var(--bg); }
.btn-green:hover { opacity: 0.9; }
.btn-orange { background: var(--orange); color: var(--bg); }
.btn-orange:hover { opacity: 0.9; }
.btn-ghost {
background: var(--surface-hover);
color: var(--text);
border: 1px solid var(--border);
}
.btn-ghost:hover { background: var(--border); }
.btn-row { display: flex; gap: 6px; }
.btn-row .btn { flex: 1; }
.output-area {
flex: 1;
display: flex;
flex-direction: column;
padding: 24px;
overflow-y: auto;
}
.output-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.8px;
color: var(--text-dim);
margin-bottom: 12px;
}
.cmd-block {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
margin-bottom: 12px;
overflow: hidden;
transition: border-color 0.3s;
}
.cmd-block.just-copied { border-color: var(--green); }
.cmd-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 14px;
background: var(--surface-hover);
border-bottom: 1px solid var(--border);
}
.cmd-label {
font-size: 12px;
font-weight: 600;
color: var(--text-dim);
}
.cmd-step {
font-size: 11px;
color: var(--text-dim);
background: var(--bg);
padding: 2px 8px;
border-radius: 10px;
}
.copy-btn {
padding: 4px 12px;
font-size: 11px;
background: var(--accent);
color: var(--bg);
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
transition: all 0.15s;
}
.copy-btn:hover { background: var(--accent-hover); }
.copy-btn.copied { background: var(--green); }
.cmd-body {
padding: 12px 14px;
font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', 'Menlo', monospace;
font-size: 13px;
line-height: 1.8;
color: var(--cyan);
user-select: all;
white-space: pre-wrap;
word-break: break-all;
}
.copy-all-bar {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
}
.copy-all-btn {
padding: 8px 20px;
font-size: 13px;
font-weight: 500;
background: var(--accent);
color: var(--bg);
border: none;
border-radius: 7px;
cursor: pointer;
transition: all 0.15s;
}
.copy-all-btn:hover { background: var(--accent-hover); }
.copy-all-btn.copied { background: var(--green); }
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex: 1;
color: var(--text-dim);
gap: 8px;
}
.empty-state .icon { font-size: 40px; opacity: 0.3; }
.empty-state .text { font-size: 14px; }
.history-item {
padding: 8px 12px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
margin-bottom: 6px;
font-family: 'SF Mono', monospace;
font-size: 11px;
color: var(--text-dim);
cursor: pointer;
transition: all 0.15s;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.history-item:hover {
border-color: var(--accent);
color: var(--text);
}
</style>
</head>
<body>
<div class="header">
<h1>IonBridge Build Tool</h1>
</div>
<div class="main">
<div class="sidebar">
<div class="section">
<div class="section-title">Target</div>
<label class="field-label">Variant</label>
<select id="variant">
<option value="cp02" selected>CP02 (FPGA)</option>
<option value="cp02s">CP02S (GPU)</option>
<option value="3536">3536 / 68W (I2C)</option>
<option value="gpu_demo">GPU Demo</option>
<option value="bird">Bird</option>
</select>
<label class="field-label">Serial Port</label>
<input type="text" id="port" value="/dev/tty.usbmodem2101">
</div>
<div class="section">
<div class="section-title">Build Options</div>
<div class="checkbox-group">
<label class="checkbox-item" onclick="toggleCb(this)">
<input type="checkbox" id="opt-production"> production
</label>
<label class="checkbox-item checked" onclick="toggleCb(this)">
<input type="checkbox" id="opt-coredump" checked> coredump
</label>
</div>
</div>
<div class="section">
<div class="section-title">Flash Options</div>
<div class="checkbox-group">
<label class="checkbox-item" onclick="toggleCb(this)">
<input type="checkbox" id="opt-littlefs"> littlefs
</label>
<label class="checkbox-item" onclick="toggleCb(this)">
<input type="checkbox" id="opt-protected_data"> protected_data
</label>
<label class="checkbox-item" onclick="toggleCb(this)">
<input type="checkbox" id="opt-nvs"> nvs
</label>
<label class="checkbox-item" onclick="toggleCb(this)">
<input type="checkbox" id="opt-phy_init"> phy_init
</label>
<label class="checkbox-item" onclick="toggleCb(this)">
<input type="checkbox" id="opt-unlock"> unlock
</label>
</div>
<label class="field-label" style="margin-top:10px">PSN</label>
<input type="text" id="psn" placeholder="e.g. 1331040606001272">
<label class="field-label">Sign Key (overrides PSN)</label>
<input type="text" id="sign_key" placeholder="e.g. /Users/ching/Downloads/xxx_sign_key.pem">
</div>
<div class="section">
<div class="section-title">Generate Command</div>
<div class="actions">
<button class="btn btn-primary" onclick="gen('build')">Build</button>
<div class="btn-row">
<button class="btn btn-green" onclick="gen('flash')">Flash</button>
<button class="btn btn-orange" onclick="gen('monitor')">Monitor</button>
</div>
<button class="btn btn-ghost" onclick="gen('build_flash')">Build + Flash</button>
<button class="btn btn-ghost" onclick="gen('update_version')">Update Version</button>
<div class="btn-row">
<button class="btn btn-ghost" onclick="gen('clean')">Clean</button>
<button class="btn btn-ghost" onclick="gen('fullclean')">Full Clean</button>
</div>
</div>
</div>
<div class="section" id="historySection" style="display:none">
<div class="section-title">History</div>
<div id="history"></div>
</div>
</div>
<div class="output-area">
<div id="emptyState" class="empty-state">
<div class="icon">&#8592;</div>
<div class="text">Select an action to generate commands</div>
</div>
<div id="output" style="display:none"></div>
</div>
</div>
<script>
const STORAGE_KEY = 'ionbridge_build_gui';
const FIELDS = ['variant', 'port', 'psn', 'sign_key'];
const CHECKBOXES = ['opt-production', 'opt-coredump', 'opt-littlefs', 'opt-protected_data', 'opt-nvs', 'opt-phy_init', 'opt-unlock'];
let historyList = [];
function val(id) { return document.getElementById(id).value.trim(); }
function checked(id) { return document.getElementById(id).checked; }
function saveState() {
const state = {};
FIELDS.forEach(id => state[id] = document.getElementById(id).value);
CHECKBOXES.forEach(id => state[id] = document.getElementById(id).checked);
state.history = historyList;
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
function loadState() {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return;
try {
const state = JSON.parse(raw);
FIELDS.forEach(id => { if (state[id] !== undefined) document.getElementById(id).value = state[id]; });
CHECKBOXES.forEach(id => {
if (state[id] !== undefined) {
const cb = document.getElementById(id);
cb.checked = state[id];
cb.closest('.checkbox-item').classList.toggle('checked', state[id]);
}
});
if (state.history) {
historyList = state.history;
if (historyList.length > 0) renderHistory();
}
} catch(e) {}
}
function toggleCb(label) {
setTimeout(() => {
const cb = label.querySelector('input[type="checkbox"]');
label.classList.toggle('checked', cb.checked);
saveState();
}, 0);
}
// Auto-save on any input change
document.addEventListener('input', (e) => {
if (e.target.matches('select, input[type="text"]')) saveState();
});
document.addEventListener('change', (e) => {
if (e.target.matches('select')) saveState();
});
function buildCmd() {
let cmd = 'make build variant=' + val('variant');
if (checked('opt-production')) cmd += ' production=1';
if (!checked('opt-coredump')) cmd += ' coredump=0';
return cmd;
}
function flashCmd() {
let cmd = 'make flash';
if (checked('opt-littlefs')) cmd += ' littlefs=1';
if (checked('opt-protected_data')) cmd += ' protected_data=1';
if (checked('opt-nvs')) cmd += ' nvs=1';
if (checked('opt-phy_init')) cmd += ' phy_init=1';
if (checked('opt-unlock')) cmd += ' unlock=1';
const signKey = val('sign_key');
const psn = val('psn');
if (signKey) cmd += ' sign_key=' + signKey;
else if (psn) cmd += ' psn=' + psn;
const port = val('port');
if (port) cmd += ' PORT=' + port;
return cmd;
}
function monitorCmd() {
let cmd = 'make monitor';
const port = val('port');
if (port) cmd += ' PORT=' + port;
return cmd;
}
function gen(action) {
let commands = [];
switch (action) {
case 'build':
commands = [{label: 'Build', cmd: buildCmd()}];
break;
case 'flash':
commands = [{label: 'Flash', cmd: flashCmd()}];
break;
case 'monitor':
commands = [{label: 'Monitor', cmd: monitorCmd()}];
break;
case 'build_flash':
commands = [
{label: 'Build', cmd: buildCmd()},
{label: 'Flash', cmd: flashCmd()},
];
break;
case 'update_version':
commands = [{label: 'Update Version', cmd: 'make update_version variant=' + val('variant')}];
break;
case 'clean':
commands = [{label: 'Clean', cmd: 'make clean'}];
break;
case 'fullclean':
commands = [{label: 'Full Clean', cmd: 'make fullclean'}];
break;
}
renderOutput(commands);
addHistory(commands);
}
function renderOutput(commands) {
document.getElementById('emptyState').style.display = 'none';
const out = document.getElementById('output');
out.style.display = 'block';
const allCmds = commands.map(c => c.cmd).join('\n');
const multi = commands.length > 1;
let html = '<div class="copy-all-bar">';
html += '<div class="output-title">Generated Commands</div>';
html += '<button class="copy-all-btn" onclick="copyAll(this, ' + JSON.stringify(allCmds).replace(/"/g, '&quot;') + ')">Copy All</button>';
html += '</div>';
commands.forEach((c, i) => {
html += '<div class="cmd-block">';
html += '<div class="cmd-header">';
html += '<div style="display:flex;align-items:center;gap:8px">';
if (multi) html += '<span class="cmd-step">Step ' + (i + 1) + '</span>';
html += '<span class="cmd-label">' + c.label + '</span>';
html += '</div>';
html += '<button class="copy-btn" onclick="copyOne(this, ' + JSON.stringify(c.cmd).replace(/"/g, '&quot;') + ')">Copy</button>';
html += '</div>';
html += '<div class="cmd-body">' + escapeHtml(c.cmd) + '</div>';
html += '</div>';
});
out.innerHTML = html;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
async function copyOne(btn, text) {
await navigator.clipboard.writeText(text);
btn.textContent = 'Copied!';
btn.classList.add('copied');
btn.closest('.cmd-block').classList.add('just-copied');
setTimeout(() => {
btn.textContent = 'Copy';
btn.classList.remove('copied');
btn.closest('.cmd-block').classList.remove('just-copied');
}, 1500);
}
async function copyAll(btn, text) {
await navigator.clipboard.writeText(text);
btn.textContent = 'Copied!';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = 'Copy All';
btn.classList.remove('copied');
}, 1500);
}
function addHistory(commands) {
const text = commands.map(c => c.cmd).join(' && ');
// Avoid duplicates at top
if (historyList.length > 0 && historyList[0] === text) return;
historyList.unshift(text);
if (historyList.length > 10) historyList.pop();
renderHistory();
saveState();
}
function renderHistory() {
const section = document.getElementById('historySection');
const container = document.getElementById('history');
section.style.display = 'block';
container.innerHTML = historyList.map(cmd =>
'<div class="history-item" onclick="copyFromHistory(this, ' + JSON.stringify(cmd).replace(/"/g, '&quot;') + ')" title="Click to copy">' + escapeHtml(cmd) + '</div>'
).join('');
}
async function copyFromHistory(el, text) {
await navigator.clipboard.writeText(text);
el.style.borderColor = 'var(--green)';
el.style.color = 'var(--green)';
setTimeout(() => {
el.style.borderColor = '';
el.style.color = '';
}, 1000);
}
loadState();
</script>
</body>
</html>

View File

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
# 用法: ./extract_firmware.sh <merged_bin> [output_prefix] # 用法: ./extract_firmware.sh <merged_bin> [output_dir]
# 从合并的 bin 文件中提取 head file (firmware), tail file (IUM), 以及生成 metadata.json # 从合并的 bin 文件中提取 head file (firmware), tail file (IUM), 以及生成 metadata.json
# #
# 文件布局: # 文件布局:
@ -8,26 +8,17 @@
# 0x1dd00: metadata (blocks: uint16, last_block_size: uint8) # 0x1dd00: metadata (blocks: uint16, last_block_size: uint8)
INPUT="$1" INPUT="$1"
# 如果没有传 PREFIX使用原文件名去掉扩展名 OUTPUT_DIR="${2:-.}"
if [ -n "$2" ]; then
PREFIX="$2"
else
# 获取文件名(不含路径),然后去掉扩展名
BASENAME=$(basename "$INPUT")
PREFIX="${BASENAME%.*}"
fi
if [ -z "$INPUT" ]; then if [ -z "$INPUT" ]; then
echo "用法: $0 <merged_bin> [output_prefix]" echo "用法: $0 <merged_bin> [output_dir]"
echo "示例: $0 40_ufcs2.bin firmware" echo "示例: $0 40_ufcs2.bin /tmp/output"
echo " $0 40_ufcs2.bin # 使用原文件名作为前缀" echo " $0 40_ufcs2.bin # 输出到当前目录"
echo "" echo ""
echo "输出文件:" echo "输出文件:"
echo " {prefix}.firmware - firmware 部分" echo " firmware.bin - firmware 部分"
echo " {prefix}.ium - IUM 部分 (256 bytes)" echo " ium.bin - IUM 部分 (256 bytes)"
echo " {prefix}_metadata.json - 元数据" echo " metadata.json - 元数据"
echo ""
echo "注: 如果不指定 output_prefix将使用原文件名去掉扩展名"
exit 1 exit 1
fi fi
@ -36,6 +27,9 @@ if [ ! -f "$INPUT" ]; then
exit 1 exit 1
fi fi
# 创建输出目录(如果不存在)
mkdir -p "$OUTPUT_DIR"
# 常量定义 # 常量定义
FIRMWARE_OFFSET=$((0x4000)) # 16384 FIRMWARE_OFFSET=$((0x4000)) # 16384
IUM_OFFSET=$((0x1dc00)) # 121856 IUM_OFFSET=$((0x1dc00)) # 121856
@ -79,7 +73,7 @@ echo " 计算出 firmware 大小: $FIRMWARE_SIZE bytes"
echo "" echo ""
# 提取 head file (firmware: 从 0x4000 开始) # 提取 head file (firmware: 从 0x4000 开始)
HEAD_FILE="firmware.bin" HEAD_FILE="$OUTPUT_DIR/firmware.bin"
echo "提取 head file (firmware)..." echo "提取 head file (firmware)..."
dd if="$INPUT" of="$HEAD_FILE" bs=1 skip=$FIRMWARE_OFFSET count=$FIRMWARE_SIZE status=none dd if="$INPUT" of="$HEAD_FILE" bs=1 skip=$FIRMWARE_OFFSET count=$FIRMWARE_SIZE status=none
@ -92,7 +86,7 @@ else
fi fi
# 提取 tail file (IUM: 从 0x1dc00 开始, 256 bytes) # 提取 tail file (IUM: 从 0x1dc00 开始, 256 bytes)
TAIL_FILE="ium.bin" TAIL_FILE="$OUTPUT_DIR/ium.bin"
echo "提取 tail file (IUM)..." echo "提取 tail file (IUM)..."
dd if="$INPUT" of="$TAIL_FILE" bs=1 skip=$IUM_OFFSET count=$IUM_SIZE status=none dd if="$INPUT" of="$TAIL_FILE" bs=1 skip=$IUM_OFFSET count=$IUM_SIZE status=none
@ -105,7 +99,7 @@ else
fi fi
# 生成 metadata.json # 生成 metadata.json
METADATA_FILE="metadata.json" METADATA_FILE="$OUTPUT_DIR/metadata.json"
echo "生成 metadata.json..." echo "生成 metadata.json..."
cat > "$METADATA_FILE" << EOF cat > "$METADATA_FILE" << EOF

38
CP02/flash_guide.md Normal file
View File

@ -0,0 +1,38 @@
# IonBridge 烧录指南
所有命令在 IonBridge 项目根目录下执行(`cd /Users/ching/develop/IonBridge`)。
## 非 Secure 设备(开发板)
```bash
# Build + Flash firmware + littlefs
make build variant=cp02
make flash littlefs=1 PORT=/dev/tty.usbmodem2101
# 只烧 firmware
make build variant=cp02
make flash PORT=/dev/tty.usbmodem2101
# 查看日志
make monitor PORT=/dev/tty.usbmodem2101
```
## Secure 设备量产板Secure Boot + Flash Encryption
```bash
# Build + Flash firmware + littlefs
make build variant=cp02 production=1
make flash littlefs=1 sign_key=/Users/ching/Downloads/1331040606001272_sign_key.pem PORT=/dev/tty.usbmodem2101
# 只烧 littlefs不更新 firmware不需要重新 build
make flash_littlefs_partition secure=1 PORT=/dev/tty.usbmodem2101
# 查看日志
make monitor PORT=/dev/tty.usbmodem2101
```
## 备注
- `sign_key` 可用 `psn` 代替:`psn=1331040606001272`(自动查找 `sign_keys/` 下的 key
- Secure 设备用 `production=1` 构建后,`secure=1` 会自动检测
- `PORT` 根据实际设备端口修改

152
CP02/remove_chinese_comments.py Executable file
View File

@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Remove Chinese comments (// and # style) from source files."""
from __future__ import annotations
import re
import sys
from pathlib import Path
# File extensions and their comment patterns
COMMENT_PATTERNS = {
# C/C++ style
'.c': r'//.*',
'.cpp': r'//.*',
'.h': r'//.*',
'.hpp': r'//.*',
# Python style
'.py': r'#.*',
}
def get_comment_pattern(filepath: str) -> str:
"""Get comment pattern based on file extension."""
ext = Path(filepath).suffix.lower()
return COMMENT_PATTERNS.get(ext, r'//.*')
def get_comment_prefix(filepath: str) -> str:
"""Get comment prefix based on file extension."""
ext = Path(filepath).suffix.lower()
if ext == '.py':
return '#'
return '//'
def contains_chinese(text: str) -> bool:
"""Check if text contains Chinese characters."""
return bool(re.search(r'[\u4e00-\u9fff]', text))
def find_chinese_comments(filepath: str):
"""Find all lines with Chinese comments.
Returns list of (line_number, line_content) tuples.
"""
results = []
path = Path(filepath)
if not path.exists():
print(f"Error: File not found: {filepath}")
sys.exit(1)
pattern = get_comment_pattern(filepath)
with open(path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
match = re.search(pattern, line)
if match and contains_chinese(match.group()):
results.append((line_num, line.rstrip()))
return results
def remove_chinese_comments(filepath: str) -> str:
"""Remove Chinese comments from file content.
Returns the modified content.
"""
path = Path(filepath)
pattern = get_comment_pattern(filepath)
prefix = get_comment_prefix(filepath)
with open(path, 'r', encoding='utf-8') as f:
lines = f.readlines()
new_lines = []
for line in lines:
match = re.search(pattern, line)
if match and contains_chinese(match.group()):
stripped = line.lstrip()
if stripped.startswith(prefix):
# Entire line is a comment - skip it
continue
else:
# Comment is at end of code - remove just the comment
comment_start = match.start()
new_line = line[:comment_start].rstrip() + '\n'
new_lines.append(new_line)
else:
new_lines.append(line)
return ''.join(new_lines)
def main():
if len(sys.argv) < 2:
print("Usage: python remove_chinese_comments.py <file> [file2 ...]")
print(" python remove_chinese_comments.py --check <file> [file2 ...]")
print("\nOptions:")
print(" --check Only show Chinese comments without removing")
sys.exit(1)
check_only = False
files = sys.argv[1:]
if files[0] == '--check':
check_only = True
files = files[1:]
if not files:
print("Error: No files specified")
sys.exit(1)
total_found = 0
for filepath in files:
comments = find_chinese_comments(filepath)
if not comments:
print(f"\n{filepath}: No Chinese comments found")
continue
total_found += len(comments)
print(f"\n{'='*60}")
print(f"File: {filepath}")
print(f"Found {len(comments)} Chinese comment(s):")
print('-'*60)
for line_num, line in comments:
print(f" L{line_num}: {line}")
if check_only:
continue
# Ask for confirmation
print('-'*60)
response = input(f"Remove these {len(comments)} comment(s)? [y/N]: ").strip().lower()
if response == 'y':
new_content = remove_chinese_comments(filepath)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"✓ Removed {len(comments)} Chinese comment(s) from {filepath}")
else:
print(f"✗ Skipped {filepath}")
print(f"\n{'='*60}")
print(f"Total: {total_found} Chinese comment(s) found")
if __name__ == '__main__':
main()