generate_cpld_teaching_html.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. #!/usr/bin/env python3
  2. """Generate CPLD teaching HTML reports from structured content."""
  3. from __future__ import annotations
  4. import argparse
  5. import html
  6. import json
  7. import re
  8. from pathlib import Path
  9. from typing import Any
  10. ROOT = Path(__file__).resolve().parents[1]
  11. DEFAULT_CONTENT = ROOT / "workspace" / "teaching_content" / "chapters" / "cpld_teaching_content.json"
  12. def esc(value: Any) -> str:
  13. return html.escape(str(value), quote=True)
  14. def esc_text(value: Any) -> str:
  15. return html.escape(str(value), quote=False)
  16. def han_count(text: str) -> int:
  17. return sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
  18. def slugify(text: str) -> str:
  19. keep = []
  20. for ch in text.lower():
  21. if ch.isalnum():
  22. keep.append(ch)
  23. elif ch in {" ", "-", "_"}:
  24. keep.append("-")
  25. slug = "".join(keep).strip("-")
  26. return slug or "section"
  27. def load_content(path: Path) -> dict[str, Any]:
  28. data = json.loads(path.read_text(encoding="utf-8-sig"))
  29. chapters = data.get("chapters", [])
  30. if len(chapters) != 13:
  31. raise SystemExit(f"content must contain 13 chapters, got {len(chapters)}")
  32. ids = [chapter["id"] for chapter in chapters]
  33. if ids != list(range(1, 14)):
  34. raise SystemExit(f"chapter ids must be 1..13, got {ids}")
  35. return data
  36. def term_button(term: str, label: str | None = None) -> str:
  37. label = label or term
  38. return f'<button class="term" type="button" data-term="{esc(term)}">{esc(label)}</button>'
  39. TERM_ALIASES = {
  40. "cpld": ["CPLD"],
  41. "ef2": ["EF2", "EF2L45BG256B"],
  42. "td": ["TD"],
  43. "al-link": ["AL-Link", "AL-Link Mini"],
  44. "vref": ["VREF"],
  45. "jtag": ["JTAG", "TMS", "TCK", "TDI", "TDO"],
  46. "bitstream": ["bitstream", "bit", "位流"],
  47. "runbook": ["Runbook"],
  48. "verilog": ["Verilog"],
  49. "rtl": ["RTL"],
  50. "register": ["Register", "寄存器", "触发器"],
  51. "fsm": ["FSM", "状态机"],
  52. "inout": ["inout", "双向端口"],
  53. "tristate": ["Tri-state", "三态", "高阻"],
  54. "synthesis": ["Synthesis", "综合"],
  55. "simulation": ["Simulation", "仿真", "testbench"],
  56. }
  57. def is_ascii_term_char(ch: str) -> bool:
  58. return ch.isascii() and (ch.isalnum() or ch in {"_", "-"})
  59. def term_alias_pairs(glossary: dict[str, Any], allowed_terms: list[str]) -> list[tuple[str, str]]:
  60. pairs: list[tuple[str, str]] = []
  61. seen: set[tuple[str, str]] = set()
  62. for term in allowed_terms:
  63. if term not in glossary:
  64. continue
  65. aliases = [term, glossary[term].get("title", ""), *TERM_ALIASES.get(term, [])]
  66. for alias in aliases:
  67. alias = str(alias).strip()
  68. if not alias:
  69. continue
  70. key = (alias.casefold(), term)
  71. if key not in seen:
  72. seen.add(key)
  73. pairs.append((alias, term))
  74. return sorted(pairs, key=lambda item: len(item[0]), reverse=True)
  75. def alias_matches(text: str, index: int, alias: str) -> bool:
  76. end = index + len(alias)
  77. if text[index:end].casefold() != alias.casefold():
  78. return False
  79. if alias[0].isascii() and index > 0 and is_ascii_term_char(text[index - 1]):
  80. return False
  81. if alias[-1].isascii() and end < len(text) and is_ascii_term_char(text[end]):
  82. return False
  83. return True
  84. def inline_terms(text: Any, glossary: dict[str, Any], allowed_terms: list[str]) -> str:
  85. """Render plain text safely, turning only allowed non-code terms into buttons."""
  86. pairs = term_alias_pairs(glossary, allowed_terms)
  87. if not pairs:
  88. return esc_text(text)
  89. rendered: list[str] = []
  90. for part in re.split(r"(`[^`]*`)", str(text)):
  91. if part.startswith("`") and part.endswith("`") and len(part) >= 2:
  92. rendered.append(f"<code>{esc_text(part[1:-1])}</code>")
  93. continue
  94. index = 0
  95. while index < len(part):
  96. matched: tuple[str, str] | None = None
  97. for alias, term in pairs:
  98. if alias_matches(part, index, alias):
  99. matched = (alias, term)
  100. break
  101. if matched:
  102. alias, term = matched
  103. label = part[index : index + len(alias)]
  104. rendered.append(term_button(term, label))
  105. index += len(alias)
  106. else:
  107. rendered.append(esc_text(part[index]))
  108. index += 1
  109. return "".join(rendered)
  110. def paragraph(text: str) -> str:
  111. return f"<p>{esc(text)}</p>"
  112. def runbook_list(items: list[str]) -> str:
  113. return "<ol class=\"runbook-list\">" + "".join(f"<li>{esc(item)}</li>" for item in items) + "</ol>"
  114. def bullet_list(items: list[str], class_name: str) -> str:
  115. return f'<ul class="{class_name}">' + "".join(f"<li>{esc_text(item)}</li>" for item in items) + "</ul>"
  116. def chapter_learning_ladder(chapter: dict[str, Any]) -> str:
  117. items = []
  118. for item in chapter.get("learning_ladder", []):
  119. items.append(
  120. "<li>"
  121. f"<b>{esc_text(item['title'])}</b>"
  122. f"<span>{esc_text(item['body'])}</span>"
  123. "</li>"
  124. )
  125. return (
  126. '<section class="section learning-ladder" id="learning-ladder">'
  127. '<div class="section-head"><div><p class="kicker">Progression</p><h2>从浅到深的学习阶梯</h2></div>'
  128. f'<p>本章不把扩展内容孤立成术语堆,而是按入门理解、工程对象、验证证据和系统扩展逐层推进。</p></div>'
  129. '<ol class="ladder-list">'
  130. + "".join(items)
  131. + "</ol></section>"
  132. )
  133. def chapter_knowledge_system(chapter: dict[str, Any]) -> str:
  134. items = []
  135. for item in chapter.get("knowledge_system", []):
  136. items.append(
  137. '<article class="system-node">'
  138. f"<h3>{esc_text(item['title'])}</h3>"
  139. f"<p>{esc_text(item['body'])}</p>"
  140. "</article>"
  141. )
  142. return (
  143. '<section class="section knowledge-system" id="knowledge-system">'
  144. '<div class="section-head"><div><p class="kicker">Knowledge System</p><h2>本章知识系统</h2></div>'
  145. f'<p>这些节点说明本章扩展知识在 CPLD 工程里的位置:它们互相连接,而不是散落的专业名词。</p></div>'
  146. '<div class="system-grid">'
  147. + "".join(items)
  148. + "</div></section>"
  149. )
  150. def section_story(section: dict[str, Any]) -> str:
  151. fields = [
  152. "beginner_entry",
  153. "engineering_story",
  154. "mechanism_walkthrough",
  155. "verification_story",
  156. "system_extension",
  157. ]
  158. return (
  159. '<article class="section-story"><h3>完整讲解</h3>'
  160. + "".join(f"<p>{esc_text(section[key])}</p>" for key in fields)
  161. + "</article>"
  162. )
  163. def progressive_note(chapter: dict[str, Any], section: dict[str, Any]) -> str:
  164. anchors = "、".join(str(anchor) for anchor in section["anchors"][:3])
  165. terms = "、".join(chapter.get("terms", [])[:4])
  166. return (
  167. '<aside class="progressive-note">'
  168. f'<p><b>阅读推进:</b>{esc_text(section["title"])} 先落在 {esc_text(anchors)},再进入 {esc_text(terms)} 这些概念。'
  169. f'读完后应能把一个现场症状连到源码、约束、报告、波形或接线证据,而不是只记住章节标题。</p>'
  170. "</aside>"
  171. )
  172. def section_svg(chapter: dict[str, Any], section: dict[str, Any], index: int) -> str:
  173. labels = [
  174. ("入口", section["phenomenon"][:28]),
  175. ("设计理由", section["why"][:28]),
  176. ("硬件动作", section["mechanism"][:28]),
  177. ("验证", section["validation"][:28]),
  178. ]
  179. colors = ["#e8f3ff", "#f3f8e8", "#fff3dd", "#f3e8ff"]
  180. x_positions = [22, 292, 562, 832]
  181. boxes = []
  182. arrows = []
  183. for i, ((title, body), color, x) in enumerate(zip(labels, colors, x_positions)):
  184. boxes.append(
  185. f'<rect x="{x}" y="24" width="220" height="100" rx="8" fill="{color}" stroke="#b6c7d9"/>'
  186. f'<text x="{x + 110}" y="58" text-anchor="middle" class="svg-title">{esc(title)}</text>'
  187. f'<text x="{x + 110}" y="88" text-anchor="middle" class="svg-small">{esc(body)}</text>'
  188. )
  189. if i < len(labels) - 1:
  190. arrows.append(
  191. f'<path d="M{x + 224} 74 H{x_positions[i + 1] - 10}" stroke="#5d7897" stroke-width="2" marker-end="url(#arrow-{chapter["id"]}-{index})"/>'
  192. )
  193. return (
  194. f'<figure class="svg-card" aria-label="{esc(section["title"])} 因果链">'
  195. f'<svg viewBox="0 0 1080 148" role="img">'
  196. f'<defs><marker id="arrow-{chapter["id"]}-{index}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">'
  197. '<path d="M 0 0 L 10 5 L 0 10 z" fill="#5d7897"/></marker></defs>'
  198. + "".join(boxes + arrows)
  199. + "</svg>"
  200. + f"<figcaption>{esc(chapter['short'])} · {esc(section['title'])} 的因果链,不用模板句替代本工程锚点。</figcaption>"
  201. + "</figure>"
  202. )
  203. INTEGRATED_SVG_NODES = {
  204. 1: {
  205. 1: [
  206. ("输入资料", "安装器 / 许可 / 手册"),
  207. ("可改工程", "workspace 源码与约束"),
  208. ("工具输出", "run / log / 位流"),
  209. ("交付回执", "HTML / 校验 / 备份"),
  210. ],
  211. 2: [
  212. ("目标供电", "板卡先独立上电"),
  213. ("VREF", "只检测目标电压"),
  214. ("JTAG", "TMS/TCK/TDI/TDO"),
  215. ("TD Refresh", "再识别器件"),
  216. ],
  217. 3: [
  218. ("Top", "端口与时钟复位"),
  219. ("Control", "字节事务编排"),
  220. ("BitShift", "SCL/SDA 位级波形"),
  221. ("Testbench", "EEPROM 模型验证"),
  222. ],
  223. 4: [
  224. ("当前 bit", "I2C EEPROM demo"),
  225. ("素材模块", "PID / UART 可教学"),
  226. ("综合边界", "AutoExcluded 不进位流"),
  227. ("后续集成", "闭环温控需另接"),
  228. ],
  229. },
  230. 2: {
  231. 1: [
  232. ("posedge", "时钟沿更新寄存器"),
  233. ("Go", "发起跨模块握手"),
  234. ("Trans_Done", "位级模块完成回传"),
  235. ("下一拍", "FSM 再推进"),
  236. ],
  237. 2: [
  238. ("SDA 低", "CPLD 主动拉低"),
  239. ("SDA 高", "主机释放为 Z"),
  240. ("上拉", "电阻或 pullup 拉高"),
  241. ("ACK", "从机在第 9 拍拉低"),
  242. ],
  243. 3: [
  244. ("注释", "50MHz 只给人看"),
  245. ("参数", "25MHz 参与综合"),
  246. ("4 相计数", "一个 bit 分四拍"),
  247. ("示波器", "以真实周期收口"),
  248. ],
  249. 4: [
  250. ("顶层可达", "top 向下追实例"),
  251. ("综合裁剪", "未实例化不保留"),
  252. ("资源统计", "DSP 0 是证据"),
  253. ("下板行为", "只等于当前 bit"),
  254. ],
  255. },
  256. }
  257. def integrated_section_svg(chapter: dict[str, Any], section: dict[str, Any], index: int) -> str:
  258. nodes = INTEGRATED_SVG_NODES.get(chapter["id"], {}).get(index)
  259. if nodes is None:
  260. nodes = [
  261. ("现场", section["phenomenon"][:18]),
  262. ("原因", section["why"][:18]),
  263. ("机制", section["mechanism"][:18]),
  264. ("验证", section["validation"][:18]),
  265. ]
  266. colors = ["#e8f3ff", "#eef8f0", "#fff5e6", "#f2edff"]
  267. x_positions = [24, 292, 560, 828]
  268. boxes = []
  269. arrows = []
  270. for node_index, ((title, body), color, x) in enumerate(zip(nodes, colors, x_positions)):
  271. boxes.append(
  272. f'<rect x="{x}" y="24" width="212" height="112" rx="8" fill="{color}" stroke="#b6c7d9"/>'
  273. f'<text x="{x + 106}" y="60" text-anchor="middle" class="svg-title">{esc_text(title)}</text>'
  274. f'<text x="{x + 106}" y="94" text-anchor="middle" class="svg-small">{esc_text(body)}</text>'
  275. )
  276. if node_index < len(nodes) - 1:
  277. arrows.append(
  278. f'<path d="M{x + 216} 82 H{x_positions[node_index + 1] - 10}" stroke="#5d7897" stroke-width="2" marker-end="url(#integrated-arrow-{chapter["id"]}-{index})"/>'
  279. )
  280. return (
  281. '<div class="visual-figure-block">'
  282. '<h3>结构图</h3>'
  283. f'<figure class="svg-card integrated-figure" aria-label="{esc(section["title"])} 结构图">'
  284. f'<svg viewBox="0 0 1068 164" role="img">'
  285. f'<defs><marker id="integrated-arrow-{chapter["id"]}-{index}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">'
  286. '<path d="M 0 0 L 10 5 L 0 10 z" fill="#5d7897"/></marker></defs>'
  287. + "".join(boxes + arrows)
  288. + "</svg>"
  289. + f"<figcaption>{esc_text(section['title'])} 的阅读顺序:先看现象在哪一层出现,再回到本工程锚点验证。</figcaption>"
  290. + "</figure></div>"
  291. )
  292. def anchor_role(anchor: Any) -> tuple[str, str]:
  293. value = str(anchor)
  294. lower = value.lower()
  295. if lower.endswith(".v") or "user_source" in lower:
  296. return ("源码结构或模块边界", "把源码存在误认为已进入当前 bit,会导致下板现象和文档结论对不上。")
  297. if "user_sim" in lower or "tb" in lower or "testbench" in lower:
  298. return ("仿真入口和可观察波形", "跳过仿真会让请求、握手、ACK、SDA 释放这些问题直接混到板级排障里。")
  299. if lower.endswith(".adc") or "iic.adc" in lower or "uart.adc" in lower:
  300. return ("引脚约束、电气属性和上拉设置", "约束版本看错会让测量点、IO 标准和 PULLUP 判断全部漂移。")
  301. if "alink" in lower or "vref" in lower or "tms" in lower or "tck" in lower:
  302. return ("下载器接线和目标电压依据", "把 VREF 当供电或漏接 GND,会在 TD 识别阶段失败,改 RTL 没用。")
  303. if "anchor_index" in lower or "autoexcluded" in lower or "dsp" in lower:
  304. return ("当前工程报告和综合边界", "把 AutoExcluded 或 DSP 0 看漏,会把素材模块误说成已综合功能。")
  305. if "scl_cnt_m" in lower:
  306. return ("SCL 分频公式和真实时钟关系", "注释和参数混用会让 100kHz 目标变成另一个周期。")
  307. if "trans_done" in lower or "write_byte" in lower:
  308. return ("跨模块握手和 FSM 推进点", "按软件函数理解会误判为同一拍完成 I2C 发送。")
  309. return ("工程事实锚点", "不核对这个锚点,后续验证会停留在经验判断。")
  310. def integrated_anchor_table(section: dict[str, Any], glossary: dict[str, Any], terms: list[str]) -> str:
  311. rows = []
  312. for anchor in section["anchors"]:
  313. proves, risk = anchor_role(anchor)
  314. rows.append(
  315. "<tr>"
  316. f"<td><code>{esc_text(anchor)}</code></td>"
  317. f"<td>{inline_terms(proves, glossary, terms)}</td>"
  318. f"<td>{inline_terms(risk, glossary, terms)}</td>"
  319. "</tr>"
  320. )
  321. return (
  322. '<div class="integrated-table-block"><h3>工程锚点表</h3>'
  323. '<div class="integrated-proof-table"><div class="table-wrap"><table>'
  324. "<thead><tr><th>锚点</th><th>它证明什么</th><th>看错会怎样</th></tr></thead><tbody>"
  325. + "".join(rows)
  326. + "</tbody></table></div></div></div>"
  327. )
  328. def integrated_verify_table(section: dict[str, Any], glossary: dict[str, Any], terms: list[str]) -> str:
  329. rows = [
  330. ("1", "锁定入口现象", section["phenomenon"], "先确认自己在查哪一层,避免从一开始就改错对象。"),
  331. ("2", "按锚点执行验证", section["validation"], "验证动作要能复现,不能只写“应该可以”。"),
  332. ]
  333. for offset, item in enumerate(section["runbook"], start=3):
  334. rows.append((str(offset), "Runbook 步骤", item, "每一步只排除一个变量,方便失败后继续定位。"))
  335. rows.append((str(len(rows) + 1), "记录边界", section["consequence"], "把误判后果写进回执,后续章节才知道哪些结论仍待下板或仿真。"))
  336. body = "".join(
  337. "<tr>"
  338. f"<td>{esc_text(step)}</td>"
  339. f"<td>{inline_terms(action, glossary, terms)}</td>"
  340. f"<td>{inline_terms(detail, glossary, terms)}</td>"
  341. f"<td>{inline_terms(reason, glossary, terms)}</td>"
  342. "</tr>"
  343. for step, action, detail, reason in rows
  344. )
  345. return (
  346. '<div class="integrated-table-block"><h3>验证与排障</h3>'
  347. '<div class="verify-table"><div class="table-wrap"><table>'
  348. "<thead><tr><th>步骤</th><th>动作</th><th>本节怎么做</th><th>为什么这样做</th></tr></thead><tbody>"
  349. + body
  350. + "</tbody></table></div></div></div>"
  351. )
  352. def integrated_mechanism(chapter: dict[str, Any], section: dict[str, Any], glossary: dict[str, Any]) -> str:
  353. terms = chapter.get("terms", [])
  354. paragraphs = [
  355. section["why"],
  356. section["mechanism"],
  357. f"如果这一步判断错,直接后果是:{section['consequence']}",
  358. section.get("system_extension", ""),
  359. ]
  360. return (
  361. '<article class="integrated-mechanism"><h3>机制拆解</h3>'
  362. + "".join(f"<p>{inline_terms(text, glossary, terms)}</p>" for text in paragraphs if text)
  363. + "</article>"
  364. )
  365. def chapter_sections_integrated(chapter: dict[str, Any], glossary: dict[str, Any]) -> str:
  366. parts = []
  367. terms = chapter.get("terms", [])
  368. for i, section in enumerate(chapter["sections"], start=1):
  369. anchor_comments = "".join(f"<!-- anchor: {str(anchor)} -->" for anchor in section["anchors"])
  370. scene = (
  371. f"{section['phenomenon']} 先不要急着背术语,先把这个现象放回 "
  372. f"{'、'.join(str(anchor) for anchor in section['anchors'][:2])} 这些本工程证据里看。"
  373. )
  374. parts.append(
  375. f'<section class="section depth-section" id="s{i}" data-section-title="{esc(section["title"])}">'
  376. f"{anchor_comments}"
  377. f'<div class="section-head"><div><p class="kicker">第{chapter["id"]}章 · 第{i}节</p><h2>{esc(section["title"])}</h2></div>'
  378. '<p class="section-summary">本节采用图文交织结构:先定位现场,再看结构图、锚点表和验证步骤,术语只在正文语境里点击。</p></div>'
  379. '<div class="integrated-section">'
  380. '<article class="scene-lead"><h3>先看现场</h3>'
  381. f"<p>{inline_terms(scene, glossary, terms)}</p></article>"
  382. '<div class="visual-explain-grid">'
  383. f"{integrated_mechanism(chapter, section, glossary)}"
  384. f"{integrated_section_svg(chapter, section, i)}"
  385. "</div>"
  386. f"{integrated_anchor_table(section, glossary, terms)}"
  387. f"{integrated_verify_table(section, glossary, terms)}"
  388. "</div>"
  389. "</section>"
  390. )
  391. return "\n".join(parts)
  392. def chapter_sections_for(chapter: dict[str, Any], glossary: dict[str, Any]) -> str:
  393. if chapter["id"] in {1, 2}:
  394. return chapter_sections_integrated(chapter, glossary)
  395. return chapter_sections(chapter, glossary)
  396. def top_map(chapter: dict[str, Any], series: list[dict[str, Any]]) -> str:
  397. nearby = [c for c in series if abs(c["id"] - chapter["id"]) <= 1 or c["id"] in {1, 13}]
  398. nodes = []
  399. for item in nearby:
  400. active = " active" if item["id"] == chapter["id"] else ""
  401. nodes.append(
  402. f'<a class="map-node{active}" href="{esc(item["file"])}">'
  403. f'<span>ch{item["id"]}</span><b>{esc(item["short"])}</b><small>{esc(item["goal"][:46])}</small></a>'
  404. )
  405. return '<div class="learning-map">' + "".join(nodes) + "</div>"
  406. def interaction_html(kind: str, chapter: dict[str, Any]) -> str:
  407. if kind == "scl-calculator":
  408. return """
  409. <section class="tool-panel" id="tool-scl">
  410. <h2>SCL 分频计算器</h2>
  411. <p>输入系统时钟和目标 I2C SCL,计算 <code>SCL_CNT_M = SYS_CLOCK / SCL_CLOCK / 4 - 1</code>。注意:当前源码参数是 25MHz,而顶层注释写 50MHz,必须用真实时钟复核。</p>
  412. <div class="calc-grid">
  413. <label>SYS_CLOCK (MHz)<input id="sclSysClock" type="number" value="25" min="1" step="1"></label>
  414. <label>SCL_CLOCK (kHz)<input id="sclTarget" type="number" value="100" min="1" step="1"></label>
  415. <button id="sclCalcBtn" type="button">计算</button>
  416. </div>
  417. <pre id="sclCalcResult" class="result-box"></pre>
  418. </section>
  419. """
  420. if kind == "i2c-frame":
  421. return """
  422. <section class="tool-panel" id="tool-i2c-frame">
  423. <h2>I2C 地址帧计算器</h2>
  424. <p>用它区分 7-bit 地址、8-bit 写帧和读方向最低位,避免把 <code>8'h50</code> 与 <code>8'hA0</code> 当成同一个语义。</p>
  425. <div class="calc-grid">
  426. <label>7-bit 地址(hex)<input id="i2cAddr7" value="50"></label>
  427. <label>寄存器地址(hex)<input id="i2cReg" value="10"></label>
  428. <button id="i2cFrameBtn" type="button">生成帧</button>
  429. </div>
  430. <pre id="i2cFrameResult" class="result-box"></pre>
  431. </section>
  432. """
  433. if kind in {"transaction-stepper", "top-transaction"}:
  434. return """
  435. <section class="tool-panel" id="tool-transaction">
  436. <h2>I2C 事务步进器</h2>
  437. <p>点击步骤查看 control FSM 与 bit_shift 的责任分界。写事务从请求开始,逐字节等待 <code>Trans_Done</code>。</p>
  438. <div class="stepper" id="transactionStepper">
  439. <button type="button" data-step="0">wrreg_req</button>
  440. <button type="button" data-step="1">device_id</button>
  441. <button type="button" data-step="2">reg_addr</button>
  442. <button type="button" data-step="3">wrdata</button>
  443. <button type="button" data-step="4">ACK 汇总</button>
  444. </div>
  445. <div id="transactionStepText" class="decision-path">选择一个步骤查看说明。</div>
  446. </section>
  447. """
  448. if kind == "pin-compare":
  449. return """
  450. <section class="tool-panel" id="tool-pin">
  451. <h2>引脚约束对照</h2>
  452. <p>约束和报告不一致时,不要下板;先确认 active constraint 并重跑报告。</p>
  453. <div class="table-wrap"><table>
  454. <thead><tr><th>信号</th><th>iic.adc</th><th>锚点索引记录的报告</th><th>处理</th></tr></thead>
  455. <tbody>
  456. <tr><td>Clk</td><td>J1</td><td>A10</td><td>停止下板,确认当前工程</td></tr>
  457. <tr><td>Rst_n</td><td>N6</td><td>E15</td><td>确认 active ADC</td></tr>
  458. <tr><td>i2c_sclk</td><td>T13</td><td>J2</td><td>重跑 P&R 报告</td></tr>
  459. <tr><td>i2c_sdat</td><td>T12</td><td>N9</td><td>更新回执</td></tr>
  460. </tbody>
  461. </table></div>
  462. </section>
  463. """
  464. if kind == "pid-scheduler":
  465. return """
  466. <section class="tool-panel" id="tool-pid">
  467. <h2>PID 24 通道调度可视化</h2>
  468. <p>三个 DSP 不是每通道独占,而是在 24 个通道间时分复用。一次 sample_tick 后依次经历 S_MULT、S_ACC、S_UPDATE。</p>
  469. <div class="pid-grid" id="pidScheduler"></div>
  470. </section>
  471. """
  472. if kind == "debug-tree":
  473. return """
  474. <section class="tool-panel" id="tool-debug">
  475. <h2>烧写排障决策树</h2>
  476. <p>从 TD 错误文本进入不同分支;不要同时重装驱动、改线、换 bit 和改 RTL。</p>
  477. <div class="debug-tree" id="debugTree">
  478. <button type="button" data-node="nohw">No hardware</button>
  479. <button type="button" data-node="usb">USB Cable is connected</button>
  480. <button type="button" data-node="crc">CRC / Chip ID</button>
  481. <button type="button" data-node="ok">下载成功但无功能</button>
  482. </div>
  483. <div id="debugPath" class="decision-path">点击错误文本查看 Runbook。</div>
  484. </section>
  485. """
  486. if kind == "waveform-ladder":
  487. return """
  488. <section class="tool-panel" id="tool-waveform">
  489. <h2>波形定位阶梯</h2>
  490. <div class="ladder">
  491. <span>请求 wr/rd</span><span>control state/cnt</span><span>Go/Cmd</span><span>Trans_Done</span><span>SCL/SDA</span><span>ACK/RW_Done</span>
  492. </div>
  493. </section>
  494. """
  495. if kind == "integration-map":
  496. return """
  497. <section class="tool-panel" id="tool-integration">
  498. <h2>温控集成路线</h2>
  499. <div class="ladder">
  500. <span>I2C demo</span><span>传感器读回</span><span>UART 状态</span><span>单通道 PID</span><span>多通道 PID</span><span>PWM 空载</span><span>闭环</span>
  501. </div>
  502. </section>
  503. """
  504. if kind == "uart-plan":
  505. return """
  506. <section class="tool-panel" id="tool-uart">
  507. <h2>UART 接入前检查</h2>
  508. <div class="check-grid"><div>顶层有 txd</div><div>使用 uart.adc</div><div>波特率分频匹配真实 Clk</div><div>日志只在低频事件发送</div></div>
  509. </section>
  510. """
  511. if kind == "td-flow":
  512. return """
  513. <section class="tool-panel" id="tool-td">
  514. <h2>TD Flow 检查链</h2>
  515. <div class="ladder"><span>工程/器件</span><span>综合资源</span><span>P&R</span><span>Timing</span><span>Bitstream</span><span>Download</span></div>
  516. </section>
  517. """
  518. if kind == "rtl-map":
  519. return """
  520. <section class="tool-panel" id="tool-rtl">
  521. <h2>RTL 分层图</h2>
  522. <div class="ladder"><span>top</span><span>i2c_control</span><span>i2c_bit_shift</span><span>SCL/SDA</span><span>EEPROM model</span></div>
  523. </section>
  524. """
  525. return """
  526. <section class="tool-panel" id="tool-env">
  527. <h2>环境检查清单</h2>
  528. <div class="check-grid"><div>TD 工具</div><div>EF2 板卡</div><div>AL-Link Mini</div><div>VREF/GND/JTAG</div><div>工程源码</div><div>验证回执</div></div>
  529. </section>
  530. """
  531. def chapter_synthesis(chapter: dict[str, Any]) -> str:
  532. section_names = "、".join(section["title"] for section in chapter["sections"])
  533. anchor_names = "、".join(str(anchor) for section in chapter["sections"] for anchor in section["anchors"][:2])
  534. review_items = "".join(
  535. f"<li><b>{esc_text(section['title'])}</b>:先看 <code>{esc_text(section['anchors'][0])}</code>,再执行验证动作:{esc_text(section['validation'])}</li>"
  536. for section in chapter["sections"]
  537. )
  538. focus_extra = ""
  539. if chapter["id"] == 5:
  540. focus_extra = (
  541. "<p>本章还要特别强调位级时序的可计算性:每一个 SCL 周期都能拆回 div_cnt、sclk_plus、cnt 和 SDA 输出使能,"
  542. "每一个 ACK 都能拆回主机释放 SDA、从机拉低和 control 层汇总 NACK。读者复查 ch5 时,不能只说“bit_shift 产生 I2C 波形”,"
  543. "而要能逐拍指出 cnt=0/1/2/3 分别改变什么,为什么 8 个 bit 需要 32 个相位,以及为什么 open-drain 表达式不能被普通 output 代替。"
  544. "如果 SCL 频率错,第一证据是周期测量;如果 ACK 错,第一证据是第 9 拍 SDA;如果读回错,第一证据是读阶段主机是否释放 SDA。这些失败签名都必须能从波形直接指认。"
  545. "复查时还要把源码中的每个相位编号写到截图旁边,形成可复用的调试笔记。这样下一次遇到无 ACK、频率偏差或读回异常时,可以直接按相位定位,并减少盲改代码和重复试错。</p>"
  546. "<p>本章的一个关键训练动作,是把公式、状态和板级波形放在同一张纸上。公式给出 SCL_CNT_M,状态机给出 cnt 和 Cmd 的推进,板级波形给出真实 SCL/SDA。"
  547. "三者只要有一个对不上,就不能继续往 control FSM 或 EEPROM 模型上猜。特别是 25MHz 与 50MHz 的差异,看起来只是注释问题,实际会直接改变 SCL 周期;"
  548. "SDA 的开漏写法看起来只是 Verilog 表达式,实际决定主从是否会总线争用。读者做完本章后,应能拿到任意一段 I2C 波形,反推出当前处在 START、写 bit、读 bit、ACK 还是 STOP,而不是只说“总线上有跳变”。</p>"
  549. )
  550. elif chapter["id"] == 6:
  551. focus_extra = (
  552. "<p>本章的复盘重点是 control FSM 与 bit_shift 的分工:control 不直接制造 SCL/SDA 波形,它负责选择下一次字节动作;bit_shift 不理解 EEPROM 事务,它只执行 Cmd 组合。"
  553. "因此排障时要先问请求是否进入 control,再问 Go 是否启动 bit_shift,再问 Trans_Done 是否回到 control,最后才问 ACK 汇总是否表示失败。"
  554. "addr_mode=0 的字节交换、ack <= ack | ack_o 的失败汇总、repeated START 的读流程,都是这种分工下的具体结果。"
  555. "读者若把它们当作孤立语句背下来,下一次换成 16-bit 地址 EEPROM 或温度传感器寄存器时仍会出错;只有把它们放回事务编排模型,才知道哪些地方需要改、哪些地方不能改。</p>"
  556. )
  557. elif chapter["id"] == 8:
  558. focus_extra = (
  559. "<p>本章还要特别强调仿真证据的层级:testbench 不是为了让页面显得完整,而是为了在没有真实板卡干扰时证明 RTL 的事务顺序。"
  560. "读者复查 ch8 时,应能说明哪一个 task 触发写、哪一个等待语句保证 EEPROM 写周期、哪个模型负责 ACK、哪个波形能证明主机释放了 SDA。"
  561. "如果这些证据缺失,就不应进入下载器、电源和线序排查。</p>"
  562. )
  563. return (
  564. '<section class="section synthesis" id="chapter-synthesis">'
  565. f'<div class="section-head"><div><p class="kicker">Chapter Synthesis</p><h2>本章串讲与验收口径</h2></div>'
  566. f'<p>本章围绕 {esc_text(section_names)} 展开,最终都要回到本工作区可验证证据。</p></div>'
  567. '<div class="deep-dive">'
  568. f'<p>学习本章时,请先把每个专节看成一个排障入口,而不是孤立知识点。{esc_text(section_names)} 这些主题的共同目标,是让读者知道从一个现象出发,应该先查哪份源码、哪条约束、哪个 TD 报告、哪段 testbench 或哪根线缆。只要不能指出证据位置,说明还停留在概念层。</p>'
  569. f'<p>本章的核心锚点包括 {esc_text(anchor_names)}。这些锚点不是引用装饰,而是现场操作的检查点:文档中的每个结论都应能被其中某个锚点支撑。若未来工程版本变化,维护者应优先更新锚点和对应验证步骤,再重新生成 HTML,而不是只改页面文字。</p>'
  570. '<p>验收时按三层判断:第一,正文是否能讲清前因后果;第二,交互工具和 SVG 是否帮助定位而非制造视觉噪声;第三,Runbook 是否能让另一个人复现同样检查。只有三层都满足,才算达到“零基础到下板”的教学目标。</p>'
  571. '<p>本章收尾时,要把章节标题、工程锚点和验证动作放在同一条阅读线索里,避免只记住名词,却不知道下一次打开 TD、仿真器或板卡时该先观察什么。</p>'
  572. f'<ol class="review-chain">{review_items}</ol>'
  573. '<p>如果读者只能复述概念,不能指出波形、约束、报告、源码或接线中的证据,本章就还没有达标。达标的表现是:看到一个失败现象后,能先判断它属于工具安装、下载链路、RTL 状态机、I2C 协议、电气连接、时序报告还是系统集成,并能说出第一条不破坏现场的检查动作。</p>'
  574. '<p>维护者更新本章时也要遵守同一标准:新增结论必须新增或复用锚点,新增锚点必须能被 validator 或人工审读覆盖;如果某段文字不能对应任何源码、手册、约束、报告、波形或 Runbook 步骤,它就应该被删除或改写。这样可以防止文档再次退化成“十段模板换标题”。</p>'
  575. f'<p>操作演练建议按“读源码、看约束、跑仿真、查报告、再下板”的顺序执行。本章不一定每一步都需要真实硬件,但每一步都要知道缺什么证据:源码能证明设计意图,约束能证明端口落点,仿真能证明 RTL 时序,报告能证明工具构建结果,下板只能证明当前 bit 在当前板卡和当前线缆条件下的行为。围绕 {esc_text(section_names)} 做演练时,任何一个证据缺失都要在回执里写清楚,不能把未验证内容写成已通过。</p>'
  576. f'<p>读者需要能把现场、机制和验证连在一起说清楚:例如为什么会看到错误文本、NACK、乱码、无波形、资源不匹配或输出饱和;哪个状态、哪个参数、哪根线、哪个约束或哪个工具阶段导致这个现象;以及打开 {esc_text(anchor_names)} 中的哪个文件、观察哪个信号、用哪个计算或按哪条 Runbook 分支继续。缺少任何一环,说明这个点还没有真正学会。</p>'
  577. '<p>建议每章至少做一个反例练习:故意设想一个错误输入或错误操作,然后沿着文档判断它会在哪一层暴露。比如参数写错会先体现在计算和波形,地址语义错会先体现在 ACK,约束错会先体现在管脚观测,下载器 VREF 错会先体现在 TD 识别阶段,PID 采样过快会先体现在 done 和通道调度。反例练习的目的不是鼓励破坏现场,而是让读者在真正故障出现前,已经知道第一个可验证分支在哪里。</p>'
  578. '<p>最后还要把“已验证”和“待验证”分开写。静态阅读只能证明文档引用了当前源码和摘录;脚本校验只能证明结构、锚点、术语、交互和反模板规则;浏览器检查只能证明页面可读可点;真实板卡、TD 下载、示波器和串口日志才证明硬件现场行为。任何交付结论都必须说明自己停在哪一层,这样下一位维护者才能接着往下做,而不是重新猜测整个链路。</p>'
  579. f'{focus_extra}'
  580. '</div></section>'
  581. )
  582. def chapter_sections(chapter: dict[str, Any], glossary: dict[str, Any]) -> str:
  583. parts = []
  584. for i, section in enumerate(chapter["sections"], start=1):
  585. anchor_comments = "".join(f"<!-- anchor: {str(anchor)} -->" for anchor in section["anchors"])
  586. anchors = anchor_comments + "".join(f"<code>{esc_text(anchor)}</code>" for anchor in section["anchors"])
  587. terms = "".join(term_button(term) for term in chapter.get("terms", []) if term in glossary)
  588. parts.append(
  589. f'<section class="section depth-section" id="s{i}" data-section-title="{esc(section["title"])}">'
  590. f'<div class="section-head"><div><p class="kicker">第{chapter["id"]}章 · 第{i}节</p><h2>{esc(section["title"])}</h2></div>'
  591. f'<p class="section-summary">本节从入门现象、工程事实、机制拆解、验证排障和体系扩展逐层展开,汉字数 {han_count(json.dumps(section, ensure_ascii=False))}。</p></div>'
  592. f'<div class="anchor-row">{anchors}</div>'
  593. f'<div class="term-strip">{terms}</div>'
  594. '<div class="explanation-flow">'
  595. '<article class="narrative-block"><h3>工程讲解</h3>'
  596. f'<p>{esc_text(section["phenomenon"])} {esc_text(section["why"])}</p>'
  597. f'<p>{esc_text(section["mechanism"])} 因此要注意:{esc_text(section["consequence"])}</p>'
  598. '</article>'
  599. '<aside class="evidence-panel"><h3>证据与操作</h3>'
  600. f'<p><b>验证:</b>{esc_text(section["validation"])}</p>'
  601. f'<h4>Runbook</h4>{runbook_list(section["runbook"])}'
  602. '</aside>'
  603. '</div>'
  604. f'{section_story(section)}'
  605. f'{progressive_note(chapter, section)}'
  606. f'{section_svg(chapter, section, i)}'
  607. '</section>'
  608. )
  609. return "\n".join(parts)
  610. def series_nav(chapter: dict[str, Any], chapters: list[dict[str, Any]]) -> str:
  611. links = []
  612. for item in chapters:
  613. active = " series-active" if item["id"] == chapter["id"] else ""
  614. links.append(f'<a class="{active}" href="{esc(item["file"])}">ch{item["id"]}·{esc(item["short"])}</a>')
  615. return '<nav class="series-nav" aria-label="系列导航">' + "".join(links) + "</nav>"
  616. def toc(chapter: dict[str, Any]) -> str:
  617. buttons = [
  618. f'<button type="button" data-target="s{i}">{i}. {esc(section["title"])}</button>'
  619. for i, section in enumerate(chapter["sections"], start=1)
  620. ]
  621. buttons.insert(0, '<button type="button" data-target="learning-ladder">学习阶梯</button>')
  622. buttons.insert(1, '<button type="button" data-target="knowledge-system">知识系统</button>')
  623. buttons.append('<button type="button" data-target="tool">交互工具</button>')
  624. buttons.append('<button type="button" data-target="glossary">术语表</button>')
  625. return '<aside id="tocPanel" class="toc-panel"><button id="tocClose" class="close" type="button">关闭</button><h3>目录</h3>' + "".join(buttons) + "</aside>"
  626. def glossary_html(glossary: dict[str, Any]) -> str:
  627. items = []
  628. for key, value in sorted(glossary.items()):
  629. items.append(
  630. f'<article class="glossary-item" data-key="{esc(key)}"><button class="term" type="button" data-term="{esc(key)}">{esc(value["title"])}</button>'
  631. f'<small>{esc(value["full"])} · {esc(value["layer"])}</small><p>{esc(value["desc"])}</p></article>'
  632. )
  633. return (
  634. '<section class="section" id="glossary"><div class="section-head"><div><p class="kicker">Glossary</p><h2>CPLD 术语总表</h2></div>'
  635. '<p>点击正文或术语表中的术语查看解释。说明结合本工程上下文,不做裸术语堆砌。</p></div>'
  636. '<input id="glossSearch" class="search" placeholder="搜索术语、层级或解释">'
  637. '<div class="glossary-list">' + "".join(items) + "</div></section>"
  638. )
  639. def css() -> str:
  640. return """
  641. :root{--ink:#142033;--muted:#637083;--line:#d9e3ef;--line2:#edf2f7;--accent:#0b5faa;--accent2:#0f766e;--warn:#b45309;--bg:#f7fafc;--card:#fff;--shadow:0 18px 45px rgba(20,32,51,.08);--content:1728px}
  642. *{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:linear-gradient(180deg,#fff 0,#f7fafc 520px);color:var(--ink);font:16px/1.72 "Segoe UI","Microsoft YaHei",Arial,sans-serif}body.no-scroll{overflow:hidden}
  643. h1,h2,h3,p{margin:0}h1{font-size:34px;line-height:1.12}h2{font-size:24px;line-height:1.22}h3{font-size:17px;color:#0b5faa}.topbar{position:sticky;top:0;height:60px;background:rgba(255,255,255,.9);backdrop-filter:blur(14px);border-bottom:1px solid var(--line);z-index:50}.top-inner{max-width:var(--content);height:60px;margin:auto;padding:0 16px;display:flex;align-items:center;justify-content:space-between;gap:12px}.brand{font-weight:800}.actions{display:flex;gap:8px;align-items:center}.pill{border:1px solid var(--line);background:#fff;border-radius:999px;min-height:44px;padding:8px 13px;cursor:pointer;color:#21334d}.progress{position:fixed;top:60px;left:0;height:3px;background:var(--accent);width:0;z-index:60}.series-nav{display:flex;flex-wrap:wrap;gap:7px 10px;padding:10px 16px;justify-content:center;background:#eef6ff;border-bottom:1px solid #c8ddf5}.series-nav a{color:#153754;text-decoration:none;border:1px solid #bfd6ef;background:#fff;border-radius:999px;padding:6px 10px;font-size:13px}.series-nav a.series-active{background:var(--accent);color:#fff;border-color:var(--accent)}
  644. main{max-width:var(--content);margin:auto;padding:18px 16px 70px}.hero{display:grid;grid-template-columns:1fr;gap:14px;margin:12px 0 16px}.hero-card,.hero-panel,.section,.tool-panel{background:rgba(255,255,255,.96);border:1px solid var(--line);border-radius:8px;box-shadow:var(--shadow)}.hero-card{padding:24px}.hero-card .lead{font-size:18px;margin-top:12px;color:#34455f}.hero-panel{padding:18px}.kicker{font-size:12px;text-transform:uppercase;letter-spacing:.11em;color:#2866b4;font-weight:800;margin-bottom:7px}.learning-map{display:grid;grid-template-columns:1fr;gap:10px}.map-node{display:block;text-decoration:none;color:var(--ink);border:1px solid var(--line);border-radius:8px;background:#fff;padding:12px}.map-node.active{border-color:#0b5faa;box-shadow:inset 4px 0 #0b5faa}.map-node span{font-size:12px;color:#0b5faa;font-weight:800}.map-node b{display:block}.map-node small{display:block;color:var(--muted);line-height:1.45}
  645. .section,.tool-panel{padding:22px;margin:16px 0;scroll-margin-top:84px}.section-head{display:grid;grid-template-columns:1fr;gap:10px;margin-bottom:16px}.section-summary{color:#4d5f75}.anchor-row,.term-strip{display:flex;flex-wrap:wrap;gap:8px;margin:10px 0}.anchor-row code{background:#f6f9fd;border:1px solid var(--line2);border-radius:6px;padding:4px 7px;color:#24384f}.explanation-flow{display:grid;grid-template-columns:1fr;gap:12px}.narrative-block,.evidence-panel{border:1px solid var(--line);background:#fff;border-radius:8px;padding:16px}.narrative-block p,.evidence-panel p,.evidence-panel li{color:#364961}.evidence-panel h4{margin:10px 0 0;color:#0b5faa}.runbook-list{margin:8px 0 0;padding-left:22px}.section-story{margin-top:14px;border:1px solid #d5e5f2;background:#f8fbff;border-radius:8px;padding:16px}.section-story h3{margin-bottom:8px}.section-story p{margin-top:9px;color:#30445d}.progressive-note{margin-top:14px;border-left:4px solid #0f766e;background:#f4fbf8;border-radius:8px;padding:14px 16px;color:#2d4654}.integrated-section{display:grid;grid-template-columns:1fr;gap:14px}.scene-lead,.integrated-mechanism,.visual-figure-block,.integrated-table-block{border:1px solid var(--line);background:#fff;border-radius:8px;padding:16px}.scene-lead{border-left:4px solid var(--accent2);background:#f8fffc}.scene-lead p,.integrated-mechanism p{color:#30445d;margin-top:8px}.visual-explain-grid{display:grid;grid-template-columns:1fr;gap:14px;align-items:start}.integrated-figure{margin-top:10px}.integrated-figure svg{min-width:640px}.integrated-proof-table .table-wrap,.verify-table .table-wrap{margin-top:10px}.integrated-proof-table table,.verify-table table{min-width:960px}.integrated-proof-table td:first-child{width:28%;font-weight:700}.verify-table td:first-child{width:64px;font-weight:800;color:#0b5faa}.deep-dive{margin-top:14px;border:1px solid #cfe2f4;background:#f8fbff;border-radius:8px;padding:16px}.deep-dive p{margin-top:9px;color:#30445d}.ladder-list{display:grid;grid-template-columns:1fr;gap:10px;padding:0;counter-reset:ladder}.ladder-list li{list-style:none;border:1px solid var(--line);border-radius:8px;background:#fff;padding:14px 14px 14px 48px;position:relative}.ladder-list li:before{counter-increment:ladder;content:counter(ladder);position:absolute;left:14px;top:14px;width:24px;height:24px;border-radius:50%;background:#0b5faa;color:#fff;display:grid;place-items:center;font-weight:800}.ladder-list b{display:block;color:#183451}.ladder-list span{display:block;color:#43556d}.system-grid{display:grid;grid-template-columns:1fr;gap:10px}.system-node{border:1px solid var(--line);background:#fff;border-radius:8px;padding:14px}.system-node p{color:#43556d;margin-top:5px}.svg-card{margin:14px 0 0;border:1px solid var(--line);border-radius:8px;background:#fff;padding:10px;overflow:auto}.svg-card svg{width:100%;min-width:780px;display:block}.svg-title{font-size:16px;font-weight:800;fill:#183451}.svg-small{font-size:12px;fill:#51647b}.svg-card figcaption{font-size:13px;color:var(--muted);margin-top:6px}.term{appearance:none;border:0;background:transparent;color:#0b5faa;font:inherit;font-weight:700;padding:0 .5px;margin:0 1px;border-radius:4px;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:4px}.term:hover{background:#edf6ff}.tool-panel h2{margin-bottom:8px}.calc-grid,.check-grid{display:grid;grid-template-columns:1fr;gap:10px;margin-top:12px}.calc-grid input{width:100%;min-height:44px;border:1px solid var(--line);border-radius:8px;padding:8px 10px;font:inherit}.calc-grid button,.stepper button,.debug-tree button{min-height:44px;border:1px solid var(--accent);background:var(--accent);color:#fff;border-radius:8px;padding:9px 12px;font:inherit;font-weight:700;cursor:pointer}.result-box,.decision-path{margin-top:12px;white-space:pre-wrap;background:#f0fdfa;border:1px solid #b6e2d8;color:#0f766e;border-radius:8px;padding:12px}.stepper,.debug-tree,.pid-grid,.ladder{display:grid;grid-template-columns:1fr;gap:9px;margin-top:12px}.pid-grid div,.ladder span,.check-grid div{border:1px solid var(--line);background:#fff;border-radius:8px;padding:11px}.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:8px;background:#fff;margin-top:12px}table{border-collapse:collapse;min-width:820px;width:100%}th,td{text-align:left;vertical-align:top;border-bottom:1px solid var(--line2);padding:10px 12px}th{background:#f6f9fd}.search{width:100%;min-height:44px;border:1px solid var(--line);border-radius:8px;padding:10px 12px;font:inherit;margin-bottom:12px}.glossary-list{display:grid;grid-template-columns:1fr;gap:10px;max-height:760px;overflow:auto}.glossary-item{border:1px solid var(--line);border-radius:8px;background:#fff;padding:12px}.glossary-item small{display:block;color:var(--muted);margin:5px 0}.glossary-item p{font-size:14px;color:#3d4e66}.toc-backdrop{position:fixed;inset:0;background:rgba(14,24,39,.2);display:none;z-index:80}.toc-backdrop.open{display:block}.toc-panel{position:fixed;right:16px;top:74px;width:min(420px,calc(100vw - 32px));max-height:calc(100vh - 96px);overflow:auto;background:#fff;border:1px solid var(--line);border-radius:8px;box-shadow:0 24px 80px rgba(22,36,58,.22);padding:14px;display:none;z-index:90}.toc-panel.open{display:block}.toc-panel button:not(.close){display:block;width:100%;text-align:left;border:0;background:transparent;border-radius:8px;padding:9px 10px;font:inherit;cursor:pointer}.toc-panel button:not(.close):hover{background:#f3f8fe}.close{float:right;border:1px solid var(--line);background:#fff;border-radius:999px;min-height:44px;padding:7px 11px}.tooltip{position:fixed;display:none;width:min(460px,calc(100vw - 24px));background:#fff;border:1px solid var(--line);border-radius:8px;box-shadow:0 24px 70px rgba(22,36,58,.24);padding:14px;z-index:100}.tooltip.open{display:block}.tooltip h4{margin:0 34px 4px 0}.tooltip .full{font-weight:700;color:#24384f}.tooltip .desc{color:#43556d}.tooltip .layer{display:inline-block;margin-top:8px;background:#eef6ff;border-radius:999px;padding:3px 8px;color:#315f8d}.tip-close{position:absolute;right:8px;top:8px;border:1px solid var(--line);background:#fff;border-radius:999px;min-width:36px;min-height:36px;cursor:pointer}
  646. @media (min-width:768px){h1{font-size:44px}h2{font-size:30px}.hero{grid-template-columns:1.25fr .75fr}.learning-map{grid-template-columns:repeat(3,minmax(0,1fr))}.section-head{grid-template-columns:1fr minmax(260px,.45fr)}.explanation-flow{grid-template-columns:minmax(0,1.18fr) minmax(280px,.82fr)}.visual-explain-grid{grid-template-columns:minmax(0,.88fr) minmax(360px,1.12fr)}.ladder-list,.system-grid{grid-template-columns:repeat(4,minmax(0,1fr))}.calc-grid{grid-template-columns:1fr 1fr auto}.check-grid,.stepper,.debug-tree,.pid-grid,.ladder{grid-template-columns:repeat(3,minmax(0,1fr))}.glossary-list{grid-template-columns:repeat(3,minmax(0,1fr))}}
  647. @media (min-width:1280px){h1{font-size:52px}.glossary-list{grid-template-columns:repeat(4,minmax(0,1fr))}.pid-grid{grid-template-columns:repeat(6,minmax(0,1fr))}.ladder{grid-template-columns:repeat(6,minmax(0,1fr))}}
  648. """
  649. def js(glossary: dict[str, Any]) -> str:
  650. return f"""
  651. const GLOSSARY = {json.dumps(glossary, ensure_ascii=False)};
  652. function byId(id) {{ return document.getElementById(id); }}
  653. function openToc() {{ byId('tocBackdrop').classList.add('open'); byId('tocPanel').classList.add('open'); document.body.classList.add('no-scroll'); }}
  654. function closeToc() {{ byId('tocBackdrop').classList.remove('open'); byId('tocPanel').classList.remove('open'); document.body.classList.remove('no-scroll'); }}
  655. function positionTooltip(tip, target) {{
  656. const r = target.getBoundingClientRect();
  657. const top = Math.min(window.innerHeight - tip.offsetHeight - 12, Math.max(12, r.bottom + 8));
  658. const left = Math.min(window.innerWidth - tip.offsetWidth - 12, Math.max(12, r.left));
  659. tip.style.top = top + 'px'; tip.style.left = left + 'px';
  660. }}
  661. function showTerm(term, target) {{
  662. const item = GLOSSARY[term]; if (!item) return;
  663. const tip = byId('tooltip');
  664. tip.innerHTML = `<button class="tip-close" type="button">×</button><h4>${{item.title}}</h4><div class="full">${{item.full}}</div><div class="desc">${{item.desc}}</div><span class="layer">${{item.layer}}</span>`;
  665. tip.classList.add('open');
  666. positionTooltip(tip, target);
  667. tip.querySelector('.tip-close').onclick = () => tip.classList.remove('open');
  668. }}
  669. document.addEventListener('click', (event) => {{
  670. const term = event.target.closest('.term');
  671. if (term) {{ showTerm(term.dataset.term, term); return; }}
  672. if (!event.target.closest('#tooltip')) byId('tooltip').classList.remove('open');
  673. }});
  674. window.addEventListener('scroll', () => {{
  675. const doc = document.documentElement;
  676. const max = doc.scrollHeight - doc.clientHeight;
  677. byId('progress').style.width = (max > 0 ? (doc.scrollTop / max) * 100 : 0) + '%';
  678. }});
  679. byId('tocBtn').onclick = openToc;
  680. byId('tocClose').onclick = closeToc;
  681. byId('tocBackdrop').onclick = closeToc;
  682. document.querySelectorAll('#tocPanel [data-target]').forEach(b => b.onclick = () => {{ byId(b.dataset.target).scrollIntoView({{behavior:'smooth', block:'start'}}); closeToc(); }});
  683. const search = byId('glossSearch');
  684. if (search) search.addEventListener('input', () => {{
  685. const q = search.value.trim().toLowerCase();
  686. document.querySelectorAll('.glossary-item').forEach(item => item.style.display = item.textContent.toLowerCase().includes(q) ? '' : 'none');
  687. }});
  688. const sclBtn = byId('sclCalcBtn');
  689. if (sclBtn) sclBtn.onclick = () => {{
  690. const sys = parseFloat(byId('sclSysClock').value) || 25;
  691. const tgt = parseFloat(byId('sclTarget').value) || 100;
  692. const cnt = Math.round((sys * 1000000) / (tgt * 1000) / 4 - 1);
  693. const actual = (sys * 1000000) / ((cnt + 1) * 4) / 1000;
  694. byId('sclCalcResult').textContent = `SCL_CNT_M = ${{cnt}}\\n实际 SCL ≈ ${{actual.toFixed(2)}} kHz\\n源码公式: SCL_CNT_M = SYS_CLOCK / SCL_CLOCK / 4 - 1`;
  695. }};
  696. const frameBtn = byId('i2cFrameBtn');
  697. if (frameBtn) frameBtn.onclick = () => {{
  698. const raw = byId('i2cAddr7').value.trim().replace(/^0x/i,'');
  699. const reg = byId('i2cReg').value.trim().replace(/^0x/i,'');
  700. let addr = parseInt(raw,16);
  701. if (addr > 0x7f) addr = addr >> 1;
  702. const wr = (addr << 1) & 0xfe;
  703. const rd = wr | 1;
  704. byId('i2cFrameResult').textContent = `7-bit 地址: 0x${{addr.toString(16).toUpperCase().padStart(2,'0')}}\\n8-bit 写帧: 0x${{wr.toString(16).toUpperCase().padStart(2,'0')}}\\n8-bit 读帧: 0x${{rd.toString(16).toUpperCase().padStart(2,'0')}}\\n寄存器地址: 0x${{reg.toUpperCase()}}`;
  705. }};
  706. const txText = [
  707. '顶层 wrreg_req 拉高一个时钟周期,control FSM 从 IDLE 进入 WR_REG。',
  708. 'cnt=0 发送 device_id,通常是地址写帧;ACK 失败先查地址、电源和上拉。',
  709. 'addr_mode 决定发送一个还是两个地址字节;addr_mode=0 发送原低 8 位。',
  710. '最后发送 wrdata,可组合 STO 生成停止条件。',
  711. 'ack <= ack | ack_o 汇总任意阶段 NACK;高电平是失败标志。'
  712. ];
  713. document.querySelectorAll('#transactionStepper button').forEach(btn => btn.onclick = () => byId('transactionStepText').textContent = txText[Number(btn.dataset.step)]);
  714. const debugText = {{
  715. nohw: 'No hardware:先查 USB 下载器、驱动、线缆和 TD 驱动安装,不要先改 RTL。',
  716. usb: 'USB Cable is connected:USB 侧可见,重点查目标板独立供电、VREF 接 VCC、GND 共地、JTAG 线序和 10P 1 脚。',
  717. crc: 'CRC / Chip ID:确认 bitstream 对应 EF2L45BG256B,文件未损坏,路径不是旧版本。',
  718. ok: '下载成功但无功能:继续验证复位、SCL/SDA 周期波形、地址 ACK、数据帧和当前 bit 是否只是 I2C demo。'
  719. }};
  720. document.querySelectorAll('#debugTree button').forEach(btn => btn.onclick = () => byId('debugPath').textContent = debugText[btn.dataset.node]);
  721. const pid = byId('pidScheduler');
  722. if (pid) {{
  723. for (let i=0; i<24; i++) {{
  724. const cell = document.createElement('div');
  725. cell.innerHTML = `<b>CH${{String(i).padStart(2,'0')}}</b><span>S_MULT → S_ACC → S_UPDATE</span>`;
  726. pid.appendChild(cell);
  727. }}
  728. }}
  729. """
  730. def render_chapter(data: dict[str, Any], chapter: dict[str, Any]) -> str:
  731. chapters = data["chapters"]
  732. glossary = data["glossary"]
  733. return f"""<!doctype html>
  734. <html lang="zh-CN">
  735. <head>
  736. <meta charset="utf-8">
  737. <meta name="viewport" content="width=device-width, initial-scale=1">
  738. <title>CPLD 第{chapter['id']}章 · {esc(chapter['title'])} · v1 重写版</title>
  739. <style>{css()}</style>
  740. </head>
  741. <body>
  742. <header class="topbar"><div class="top-inner"><div class="brand">CPLD 教学 · ch{chapter['id']} {esc(chapter['short'])}</div><div class="actions"><button class="pill" id="tocBtn" type="button">目录</button><a class="pill" href="#glossary">术语</a></div></div></header>
  743. <div class="progress" id="progress"></div>
  744. {series_nav(chapter, chapters)}
  745. <div id="tocBackdrop" class="toc-backdrop"></div>
  746. {toc(chapter)}
  747. <div id="tooltip" class="tooltip"></div>
  748. <main>
  749. <section class="hero" id="top">
  750. <div class="hero-card">
  751. <p class="kicker">CPLD 全链路教学 · 源码化生成</p>
  752. <h1>{esc(chapter['title'])}</h1>
  753. <p class="lead">{esc(chapter['goal'])}</p>
  754. <p class="lead">读者定位:{esc(data['audience'])}。本页拒绝模板换标题,每个专节都回到 CPLD 工作区的源码、手册摘录、约束或排障现象。</p>
  755. </div>
  756. <div class="hero-panel">
  757. <p class="kicker">学习路径</p>
  758. {top_map(chapter, chapters)}
  759. </div>
  760. </section>
  761. {chapter_learning_ladder(chapter)}
  762. {chapter_knowledge_system(chapter)}
  763. {chapter_sections_for(chapter, glossary)}
  764. {chapter_synthesis(chapter)}
  765. <div id="tool">{interaction_html(chapter.get('interactive', ''), chapter)}</div>
  766. {glossary_html(glossary)}
  767. </main>
  768. <script>{js(glossary)}</script>
  769. </body>
  770. </html>
  771. """
  772. def generate(content: Path, output_dir: Path) -> list[Path]:
  773. data = load_content(content)
  774. output_dir.mkdir(parents=True, exist_ok=True)
  775. paths: list[Path] = []
  776. for chapter in data["chapters"]:
  777. html_text = render_chapter(data, chapter)
  778. path = output_dir / chapter["file"]
  779. path.write_text(html_text, encoding="utf-8", newline="\n")
  780. paths.append(path)
  781. return paths
  782. def main() -> int:
  783. parser = argparse.ArgumentParser(description=__doc__)
  784. parser.add_argument("--content", type=Path, default=DEFAULT_CONTENT)
  785. parser.add_argument("--output-dir", type=Path, required=True)
  786. parser.add_argument("--json", action="store_true", help="print generated file metadata as JSON")
  787. args = parser.parse_args()
  788. paths = generate(args.content, args.output_dir)
  789. payload = {"generated": [{"file": p.name, "bytes": p.stat().st_size} for p in paths]}
  790. if args.json:
  791. print(json.dumps(payload, ensure_ascii=False, indent=2))
  792. else:
  793. for path in paths:
  794. print(path)
  795. return 0
  796. if __name__ == "__main__":
  797. raise SystemExit(main())