generate_cpld_teaching_html.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. from pathlib import Path
  8. from typing import Any
  9. ROOT = Path(__file__).resolve().parents[1]
  10. DEFAULT_CONTENT = ROOT / "workspace" / "teaching_content" / "chapters" / "cpld_teaching_content.json"
  11. def esc(value: Any) -> str:
  12. return html.escape(str(value), quote=True)
  13. def esc_text(value: Any) -> str:
  14. return html.escape(str(value), quote=False)
  15. def han_count(text: str) -> int:
  16. return sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
  17. def slugify(text: str) -> str:
  18. keep = []
  19. for ch in text.lower():
  20. if ch.isalnum():
  21. keep.append(ch)
  22. elif ch in {" ", "-", "_"}:
  23. keep.append("-")
  24. slug = "".join(keep).strip("-")
  25. return slug or "section"
  26. def load_content(path: Path) -> dict[str, Any]:
  27. data = json.loads(path.read_text(encoding="utf-8-sig"))
  28. chapters = data.get("chapters", [])
  29. if len(chapters) != 13:
  30. raise SystemExit(f"content must contain 13 chapters, got {len(chapters)}")
  31. ids = [chapter["id"] for chapter in chapters]
  32. if ids != list(range(1, 14)):
  33. raise SystemExit(f"chapter ids must be 1..13, got {ids}")
  34. return data
  35. def term_button(term: str, label: str | None = None) -> str:
  36. label = label or term
  37. return f'<button class="term" type="button" data-term="{esc(term)}">{esc(label)}</button>'
  38. def paragraph(text: str) -> str:
  39. return f"<p>{esc(text)}</p>"
  40. def runbook_list(items: list[str]) -> str:
  41. return "<ol class=\"runbook-list\">" + "".join(f"<li>{esc(item)}</li>" for item in items) + "</ol>"
  42. def deep_dive(chapter: dict[str, Any], section: dict[str, Any]) -> str:
  43. anchors = "、".join(str(anchor) for anchor in section["anchors"])
  44. runbook = ";".join(section["runbook"])
  45. title = section["title"]
  46. short = chapter["short"]
  47. paragraphs = [
  48. (
  49. f"把「{title}」放回第{chapter['id']}章「{short}」的工程现场,第一步不是背定义,而是把可观察现象和可修改对象分开。"
  50. f"这里的现象是:{section['phenomenon']} 这句话要先被读者转成可检查证据,例如源码行、波形、TD 报告、约束项、线缆连接或下载错误文本。"
  51. f"只有证据可定位,后面的推理才不会变成凭经验猜测。"
  52. ),
  53. (
  54. f"本节前因可以继续追到设计边界:{section['why']} 对零基础读者来说,关键不是马上掌握所有硬件术语,"
  55. f"而是知道这个边界一旦判断错,会把问题带到错误层级。比如本节的锚点包括 {anchors},它们分别承担事实来源、实现位置或排障入口的角色。"
  56. f"阅读时应把这些锚点逐一打开或在 TD/仿真/板卡上找到对应证据。"
  57. ),
  58. (
  59. f"机制层要回答“为什么硬件会这样表现”:{section['mechanism']} 这段机制不能只停留在文字,必须能落到信号变化、状态转移、工具检查或线序关系。"
  60. f"如果读者能用自己的话说出输入是什么、内部怎么传递、输出在哪里观察,就说明这一点已经从概念变成可调试模型。"
  61. ),
  62. (
  63. f"忽略这一点的后果是:{section['consequence']} 因此验证策略必须提前写清:{section['validation']} "
  64. f"现场执行时按这个顺序操作:{runbook}。每一步只改变一个变量,并记录时间、文件版本和观察结果;如果失败,回退到上一个证据完整的层级,而不是同时改源码、约束和接线。"
  65. ),
  66. (
  67. f"常见误判要单独拎出来:看到「{title}」相关异常时,不要先问“是不是板子坏了”,而要按层级问四个问题。"
  68. f"第一,现象是否真的出现,还是旧 bit、旧 HTML、旧报告造成的错觉;第二,锚点 {anchors} 中哪一个最接近当前现象;"
  69. f"第三,这个锚点对应的是工具层、RTL 层、协议层、电气层还是系统集成层;第四,有没有一个不改硬件也能复现的仿真或静态检查。"
  70. f"只有这四个问题回答完,才值得进入下一层排查。"
  71. ),
  72. (
  73. f"本节的交付标准是读者能把「{title}」讲给另一个刚接触 CPLD 的人听,并能给出一个最小实验。"
  74. f"这个实验必须包含输入条件、期望观察点、失败时的第一分支和回退方式。若实验需要真实板卡,就要明确说出 TD 工程、约束、下载器连接和观测工具;"
  75. f"若只需仿真,就要说清 testbench、关键波形和通过/失败判据。这样写出来的文档才不是摘要,而是能指导下一次真实操作的工程说明。"
  76. ),
  77. ]
  78. return (
  79. '<div class="deep-dive"><h3>工程化深挖</h3>'
  80. + "".join(f"<p>{esc_text(p)}</p>" for p in paragraphs)
  81. + "</div>"
  82. )
  83. def section_svg(chapter: dict[str, Any], section: dict[str, Any], index: int) -> str:
  84. labels = [
  85. ("现象", section["phenomenon"][:28]),
  86. ("前因", section["why"][:28]),
  87. ("机制", section["mechanism"][:28]),
  88. ("验证", section["validation"][:28]),
  89. ]
  90. colors = ["#e8f3ff", "#f3f8e8", "#fff3dd", "#f3e8ff"]
  91. x_positions = [22, 292, 562, 832]
  92. boxes = []
  93. arrows = []
  94. for i, ((title, body), color, x) in enumerate(zip(labels, colors, x_positions)):
  95. boxes.append(
  96. f'<rect x="{x}" y="24" width="220" height="100" rx="8" fill="{color}" stroke="#b6c7d9"/>'
  97. f'<text x="{x + 110}" y="58" text-anchor="middle" class="svg-title">{esc(title)}</text>'
  98. f'<text x="{x + 110}" y="88" text-anchor="middle" class="svg-small">{esc(body)}</text>'
  99. )
  100. if i < len(labels) - 1:
  101. arrows.append(
  102. 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})"/>'
  103. )
  104. return (
  105. f'<figure class="svg-card" aria-label="{esc(section["title"])} 因果链">'
  106. f'<svg viewBox="0 0 1080 148" role="img">'
  107. 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">'
  108. '<path d="M 0 0 L 10 5 L 0 10 z" fill="#5d7897"/></marker></defs>'
  109. + "".join(boxes + arrows)
  110. + "</svg>"
  111. + f"<figcaption>{esc(chapter['short'])} · {esc(section['title'])} 的因果链,不用模板句替代本工程锚点。</figcaption>"
  112. + "</figure>"
  113. )
  114. def top_map(chapter: dict[str, Any], series: list[dict[str, Any]]) -> str:
  115. nearby = [c for c in series if abs(c["id"] - chapter["id"]) <= 1 or c["id"] in {1, 13}]
  116. nodes = []
  117. for item in nearby:
  118. active = " active" if item["id"] == chapter["id"] else ""
  119. nodes.append(
  120. f'<a class="map-node{active}" href="{esc(item["file"])}">'
  121. f'<span>ch{item["id"]}</span><b>{esc(item["short"])}</b><small>{esc(item["goal"][:46])}</small></a>'
  122. )
  123. return '<div class="learning-map">' + "".join(nodes) + "</div>"
  124. def interaction_html(kind: str, chapter: dict[str, Any]) -> str:
  125. if kind == "scl-calculator":
  126. return """
  127. <section class="tool-panel" id="tool-scl">
  128. <h2>SCL 分频计算器</h2>
  129. <p>输入系统时钟和目标 I2C SCL,计算 <code>SCL_CNT_M = SYS_CLOCK / SCL_CLOCK / 4 - 1</code>。注意:当前源码参数是 25MHz,而顶层注释写 50MHz,必须用真实时钟复核。</p>
  130. <div class="calc-grid">
  131. <label>SYS_CLOCK (MHz)<input id="sclSysClock" type="number" value="25" min="1" step="1"></label>
  132. <label>SCL_CLOCK (kHz)<input id="sclTarget" type="number" value="100" min="1" step="1"></label>
  133. <button id="sclCalcBtn" type="button">计算</button>
  134. </div>
  135. <pre id="sclCalcResult" class="result-box"></pre>
  136. </section>
  137. """
  138. if kind == "i2c-frame":
  139. return """
  140. <section class="tool-panel" id="tool-i2c-frame">
  141. <h2>I2C 地址帧计算器</h2>
  142. <p>用它区分 7-bit 地址、8-bit 写帧和读方向最低位,避免把 <code>8'h50</code> 与 <code>8'hA0</code> 当成同一个语义。</p>
  143. <div class="calc-grid">
  144. <label>7-bit 地址(hex)<input id="i2cAddr7" value="50"></label>
  145. <label>寄存器地址(hex)<input id="i2cReg" value="10"></label>
  146. <button id="i2cFrameBtn" type="button">生成帧</button>
  147. </div>
  148. <pre id="i2cFrameResult" class="result-box"></pre>
  149. </section>
  150. """
  151. if kind in {"transaction-stepper", "top-transaction"}:
  152. return """
  153. <section class="tool-panel" id="tool-transaction">
  154. <h2>I2C 事务步进器</h2>
  155. <p>点击步骤查看 control FSM 与 bit_shift 的责任分界。写事务从请求开始,逐字节等待 <code>Trans_Done</code>。</p>
  156. <div class="stepper" id="transactionStepper">
  157. <button type="button" data-step="0">wrreg_req</button>
  158. <button type="button" data-step="1">device_id</button>
  159. <button type="button" data-step="2">reg_addr</button>
  160. <button type="button" data-step="3">wrdata</button>
  161. <button type="button" data-step="4">ACK 汇总</button>
  162. </div>
  163. <div id="transactionStepText" class="decision-path">选择一个步骤查看说明。</div>
  164. </section>
  165. """
  166. if kind == "pin-compare":
  167. return """
  168. <section class="tool-panel" id="tool-pin">
  169. <h2>引脚约束对照</h2>
  170. <p>约束和报告不一致时,不要下板;先确认 active constraint 并重跑报告。</p>
  171. <div class="table-wrap"><table>
  172. <thead><tr><th>信号</th><th>iic.adc</th><th>锚点索引记录的报告</th><th>处理</th></tr></thead>
  173. <tbody>
  174. <tr><td>Clk</td><td>J1</td><td>A10</td><td>停止下板,确认当前工程</td></tr>
  175. <tr><td>Rst_n</td><td>N6</td><td>E15</td><td>确认 active ADC</td></tr>
  176. <tr><td>i2c_sclk</td><td>T13</td><td>J2</td><td>重跑 P&R 报告</td></tr>
  177. <tr><td>i2c_sdat</td><td>T12</td><td>N9</td><td>更新回执</td></tr>
  178. </tbody>
  179. </table></div>
  180. </section>
  181. """
  182. if kind == "pid-scheduler":
  183. return """
  184. <section class="tool-panel" id="tool-pid">
  185. <h2>PID 24 通道调度可视化</h2>
  186. <p>三个 DSP 不是每通道独占,而是在 24 个通道间时分复用。一次 sample_tick 后依次经历 S_MULT、S_ACC、S_UPDATE。</p>
  187. <div class="pid-grid" id="pidScheduler"></div>
  188. </section>
  189. """
  190. if kind == "debug-tree":
  191. return """
  192. <section class="tool-panel" id="tool-debug">
  193. <h2>烧写排障决策树</h2>
  194. <p>从 TD 错误文本进入不同分支;不要同时重装驱动、改线、换 bit 和改 RTL。</p>
  195. <div class="debug-tree" id="debugTree">
  196. <button type="button" data-node="nohw">No hardware</button>
  197. <button type="button" data-node="usb">USB Cable is connected</button>
  198. <button type="button" data-node="crc">CRC / Chip ID</button>
  199. <button type="button" data-node="ok">下载成功但无功能</button>
  200. </div>
  201. <div id="debugPath" class="decision-path">点击错误文本查看 Runbook。</div>
  202. </section>
  203. """
  204. if kind == "waveform-ladder":
  205. return """
  206. <section class="tool-panel" id="tool-waveform">
  207. <h2>波形定位阶梯</h2>
  208. <div class="ladder">
  209. <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>
  210. </div>
  211. </section>
  212. """
  213. if kind == "integration-map":
  214. return """
  215. <section class="tool-panel" id="tool-integration">
  216. <h2>温控集成路线</h2>
  217. <div class="ladder">
  218. <span>I2C demo</span><span>传感器读回</span><span>UART 状态</span><span>单通道 PID</span><span>多通道 PID</span><span>PWM 空载</span><span>闭环</span>
  219. </div>
  220. </section>
  221. """
  222. if kind == "uart-plan":
  223. return """
  224. <section class="tool-panel" id="tool-uart">
  225. <h2>UART 接入前检查</h2>
  226. <div class="check-grid"><div>顶层有 txd</div><div>使用 uart.adc</div><div>波特率分频匹配真实 Clk</div><div>日志只在低频事件发送</div></div>
  227. </section>
  228. """
  229. if kind == "td-flow":
  230. return """
  231. <section class="tool-panel" id="tool-td">
  232. <h2>TD Flow 检查链</h2>
  233. <div class="ladder"><span>工程/器件</span><span>综合资源</span><span>P&R</span><span>Timing</span><span>Bitstream</span><span>Download</span></div>
  234. </section>
  235. """
  236. if kind == "rtl-map":
  237. return """
  238. <section class="tool-panel" id="tool-rtl">
  239. <h2>RTL 分层图</h2>
  240. <div class="ladder"><span>top</span><span>i2c_control</span><span>i2c_bit_shift</span><span>SCL/SDA</span><span>EEPROM model</span></div>
  241. </section>
  242. """
  243. return """
  244. <section class="tool-panel" id="tool-env">
  245. <h2>环境检查清单</h2>
  246. <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>
  247. </section>
  248. """
  249. def chapter_synthesis(chapter: dict[str, Any]) -> str:
  250. section_names = "、".join(section["title"] for section in chapter["sections"])
  251. anchor_names = "、".join(str(anchor) for section in chapter["sections"] for anchor in section["anchors"][:2])
  252. review_questions = ";".join(
  253. f"{section['title']}:先看{section['anchors'][0]},再确认{section['validation']}"
  254. for section in chapter["sections"]
  255. )
  256. focus_extra = ""
  257. if chapter["id"] == 5:
  258. focus_extra = (
  259. "<p>本章还要特别强调位级时序的可计算性:每一个 SCL 周期都能拆回 div_cnt、sclk_plus、cnt 和 SDA 输出使能,"
  260. "每一个 ACK 都能拆回主机释放 SDA、从机拉低和 control 层汇总 NACK。读者复查 ch5 时,不能只说“bit_shift 产生 I2C 波形”,"
  261. "而要能逐拍指出 cnt=0/1/2/3 分别改变什么,为什么 8 个 bit 需要 32 个相位,以及为什么 open-drain 表达式不能被普通 output 代替。"
  262. "如果 SCL 频率错,第一证据是周期测量;如果 ACK 错,第一证据是第 9 拍 SDA;如果读回错,第一证据是读阶段主机是否释放 SDA。这些失败签名都必须能从波形直接指认。"
  263. "复查时还要把源码中的每个相位编号写到截图旁边,形成可复用的调试笔记。这样下一次遇到无 ACK、频率偏差或读回异常时,可以直接按相位定位,并减少盲改代码和重复试错。</p>"
  264. )
  265. elif chapter["id"] == 8:
  266. focus_extra = (
  267. "<p>本章还要特别强调仿真证据的层级:testbench 不是为了让页面显得完整,而是为了在没有真实板卡干扰时证明 RTL 的事务顺序。"
  268. "读者复查 ch8 时,应能说明哪一个 task 触发写、哪一个等待语句保证 EEPROM 写周期、哪个模型负责 ACK、哪个波形能证明主机释放了 SDA。"
  269. "如果这些证据缺失,就不应进入下载器、电源和线序排查。</p>"
  270. )
  271. return (
  272. '<section class="section synthesis" id="chapter-synthesis">'
  273. f'<div class="section-head"><div><p class="kicker">Chapter Synthesis</p><h2>本章串讲与验收口径</h2></div>'
  274. f'<p>本章围绕 {esc_text(section_names)} 展开,最终都要回到本工作区可验证证据。</p></div>'
  275. '<div class="deep-dive">'
  276. f'<p>学习本章时,请先把每个专节看成一个排障入口,而不是孤立知识点。{esc_text(section_names)} 这些主题的共同目标,是让读者知道从一个现象出发,应该先查哪份源码、哪条约束、哪个 TD 报告、哪段 testbench 或哪根线缆。只要不能指出证据位置,说明还停留在概念层。</p>'
  277. f'<p>本章的核心锚点包括 {esc_text(anchor_names)}。这些锚点不是引用装饰,而是现场操作的检查点:文档中的每个结论都应能被其中某个锚点支撑。若未来工程版本变化,维护者应优先更新锚点和对应验证步骤,再重新生成 HTML,而不是只改页面文字。</p>'
  278. '<p>验收时按三层判断:第一,正文是否能讲清前因后果;第二,交互工具和 SVG 是否帮助定位而非制造视觉噪声;第三,Runbook 是否能让另一个人复现同样检查。只有三层都满足,才算达到“零基础到下板”的教学目标。</p>'
  279. f'<p>复盘本章时建议按这个问题链自问:{esc_text(review_questions)}。这个问题链把章节标题、工程锚点和验证动作绑在一起,避免阅读后只记住名词,却不知道下一次打开 TD、仿真器或板卡时该先观察什么。</p>'
  280. '<p>如果读者只能复述概念,不能指出波形、约束、报告、源码或接线中的证据,本章就还没有达标。达标的表现是:看到一个失败现象后,能先判断它属于工具安装、下载链路、RTL 状态机、I2C 协议、电气连接、时序报告还是系统集成,并能说出第一条不破坏现场的检查动作。</p>'
  281. '<p>维护者更新本章时也要遵守同一标准:新增结论必须新增或复用锚点,新增锚点必须能被 validator 或人工审读覆盖;如果某段文字不能对应任何源码、手册、约束、报告、波形或 Runbook 步骤,它就应该被删除或改写。这样可以防止文档再次退化成“十段模板换标题”。</p>'
  282. f'<p>操作演练建议按“读源码、看约束、跑仿真、查报告、再下板”的顺序执行。本章不一定每一步都需要真实硬件,但每一步都要知道缺什么证据:源码能证明设计意图,约束能证明端口落点,仿真能证明 RTL 时序,报告能证明工具构建结果,下板只能证明当前 bit 在当前板卡和当前线缆条件下的行为。围绕 {esc_text(section_names)} 做演练时,任何一个证据缺失都要在回执里写清楚,不能把未验证内容写成已通过。</p>'
  283. f'<p>本章的最小复述标准是:读者能不看页面说出三个层次。第一层是现象,例如为什么会看到错误文本、NACK、乱码、无波形、资源不匹配或输出饱和;第二层是机制,例如哪个状态、哪个参数、哪根线、哪个约束或哪个工具阶段导致这个现象;第三层是验证,例如打开 {esc_text(anchor_names)} 中的哪个文件、观察哪个信号、用哪个计算或按哪条 Runbook 分支继续。三层缺一层,说明文档还没有真正教会这个点。</p>'
  284. '<p>建议每章至少做一个反例练习:故意设想一个错误输入或错误操作,然后沿着文档判断它会在哪一层暴露。比如参数写错会先体现在计算和波形,地址语义错会先体现在 ACK,约束错会先体现在管脚观测,下载器 VREF 错会先体现在 TD 识别阶段,PID 采样过快会先体现在 done 和通道调度。反例练习的目的不是鼓励破坏现场,而是让读者在真正故障出现前,已经知道第一个可验证分支在哪里。</p>'
  285. '<p>最后还要把“已验证”和“待验证”分开写。静态阅读只能证明文档引用了当前源码和摘录;脚本校验只能证明结构、锚点、术语、交互和反模板规则;浏览器检查只能证明页面可读可点;真实板卡、TD 下载、示波器和串口日志才证明硬件现场行为。任何交付结论都必须说明自己停在哪一层,这样下一位维护者才能接着往下做,而不是重新猜测整个链路。</p>'
  286. f'{focus_extra}'
  287. '</div></section>'
  288. )
  289. def chapter_sections(chapter: dict[str, Any], glossary: dict[str, Any]) -> str:
  290. parts = []
  291. for i, section in enumerate(chapter["sections"], start=1):
  292. anchor_comments = "".join(f"<!-- anchor: {str(anchor)} -->" for anchor in section["anchors"])
  293. anchors = anchor_comments + "".join(f"<code>{esc_text(anchor)}</code>" for anchor in section["anchors"])
  294. terms = "".join(term_button(term) for term in chapter.get("terms", []) if term in glossary)
  295. parts.append(
  296. f'<section class="section depth-section" id="s{i}" data-section-title="{esc(section["title"])}">'
  297. f'<div class="section-head"><div><p class="kicker">第{chapter["id"]}章 · 第{i}节</p><h2>{esc(section["title"])}</h2></div>'
  298. f'<p class="section-summary">本节按现象、前因、机制、后果、验证、排障和工程锚点展开,汉字数 {han_count(json.dumps(section, ensure_ascii=False))}。</p></div>'
  299. f'<div class="anchor-row">{anchors}</div>'
  300. f'<div class="term-strip">{terms}</div>'
  301. '<div class="causal-grid">'
  302. f'<article><h3>现象</h3>{paragraph(section["phenomenon"])}</article>'
  303. f'<article><h3>前因 Why</h3>{paragraph(section["why"])}</article>'
  304. f'<article><h3>机制 How</h3>{paragraph(section["mechanism"])}</article>'
  305. f'<article><h3>后果 So what</h3>{paragraph(section["consequence"])}</article>'
  306. f'<article><h3>验证</h3>{paragraph(section["validation"])}</article>'
  307. f'<article><h3>Runbook</h3>{runbook_list(section["runbook"])}</article>'
  308. '</div>'
  309. f'{deep_dive(chapter, section)}'
  310. f'{section_svg(chapter, section, i)}'
  311. '</section>'
  312. )
  313. return "\n".join(parts)
  314. def series_nav(chapter: dict[str, Any], chapters: list[dict[str, Any]]) -> str:
  315. links = []
  316. for item in chapters:
  317. active = " series-active" if item["id"] == chapter["id"] else ""
  318. links.append(f'<a class="{active}" href="{esc(item["file"])}">ch{item["id"]}·{esc(item["short"])}</a>')
  319. return '<nav class="series-nav" aria-label="系列导航">' + "".join(links) + "</nav>"
  320. def toc(chapter: dict[str, Any]) -> str:
  321. buttons = [
  322. f'<button type="button" data-target="s{i}">{i}. {esc(section["title"])}</button>'
  323. for i, section in enumerate(chapter["sections"], start=1)
  324. ]
  325. buttons.append('<button type="button" data-target="tool">交互工具</button>')
  326. buttons.append('<button type="button" data-target="glossary">术语表</button>')
  327. return '<aside id="tocPanel" class="toc-panel"><button id="tocClose" class="close" type="button">关闭</button><h3>目录</h3>' + "".join(buttons) + "</aside>"
  328. def glossary_html(glossary: dict[str, Any]) -> str:
  329. items = []
  330. for key, value in sorted(glossary.items()):
  331. items.append(
  332. f'<article class="glossary-item" data-key="{esc(key)}"><button class="term" type="button" data-term="{esc(key)}">{esc(value["title"])}</button>'
  333. f'<small>{esc(value["full"])} · {esc(value["layer"])}</small><p>{esc(value["desc"])}</p></article>'
  334. )
  335. return (
  336. '<section class="section" id="glossary"><div class="section-head"><div><p class="kicker">Glossary</p><h2>CPLD 术语总表</h2></div>'
  337. '<p>点击正文或术语表中的术语查看解释。说明结合本工程上下文,不做裸术语堆砌。</p></div>'
  338. '<input id="glossSearch" class="search" placeholder="搜索术语、层级或解释">'
  339. '<div class="glossary-list">' + "".join(items) + "</div></section>"
  340. )
  341. def css() -> str:
  342. return """
  343. :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}
  344. *{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}
  345. 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)}
  346. 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}
  347. .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}.causal-grid{display:grid;grid-template-columns:1fr;gap:12px}.causal-grid article{border:1px solid var(--line);background:#fff;border-radius:8px;padding:15px}.causal-grid p,.causal-grid li{color:#364961}.runbook-list{margin:8px 0 0;padding-left:22px}.deep-dive{margin-top:14px;border:1px solid #cfe2f4;background:#f8fbff;border-radius:8px;padding:16px}.deep-dive p{margin-top:9px;color:#30445d}.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}
  348. @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)}.causal-grid{grid-template-columns:repeat(2,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))}}
  349. @media (min-width:1280px){h1{font-size:52px}.causal-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.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))}}
  350. """
  351. def js(glossary: dict[str, Any]) -> str:
  352. return f"""
  353. const GLOSSARY = {json.dumps(glossary, ensure_ascii=False)};
  354. function byId(id) {{ return document.getElementById(id); }}
  355. function openToc() {{ byId('tocBackdrop').classList.add('open'); byId('tocPanel').classList.add('open'); document.body.classList.add('no-scroll'); }}
  356. function closeToc() {{ byId('tocBackdrop').classList.remove('open'); byId('tocPanel').classList.remove('open'); document.body.classList.remove('no-scroll'); }}
  357. function positionTooltip(tip, target) {{
  358. const r = target.getBoundingClientRect();
  359. const top = Math.min(window.innerHeight - tip.offsetHeight - 12, Math.max(12, r.bottom + 8));
  360. const left = Math.min(window.innerWidth - tip.offsetWidth - 12, Math.max(12, r.left));
  361. tip.style.top = top + 'px'; tip.style.left = left + 'px';
  362. }}
  363. function showTerm(term, target) {{
  364. const item = GLOSSARY[term]; if (!item) return;
  365. const tip = byId('tooltip');
  366. 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>`;
  367. tip.classList.add('open');
  368. positionTooltip(tip, target);
  369. tip.querySelector('.tip-close').onclick = () => tip.classList.remove('open');
  370. }}
  371. document.addEventListener('click', (event) => {{
  372. const term = event.target.closest('.term');
  373. if (term) {{ showTerm(term.dataset.term, term); return; }}
  374. if (!event.target.closest('#tooltip')) byId('tooltip').classList.remove('open');
  375. }});
  376. window.addEventListener('scroll', () => {{
  377. const doc = document.documentElement;
  378. const max = doc.scrollHeight - doc.clientHeight;
  379. byId('progress').style.width = (max > 0 ? (doc.scrollTop / max) * 100 : 0) + '%';
  380. }});
  381. byId('tocBtn').onclick = openToc;
  382. byId('tocClose').onclick = closeToc;
  383. byId('tocBackdrop').onclick = closeToc;
  384. document.querySelectorAll('#tocPanel [data-target]').forEach(b => b.onclick = () => {{ byId(b.dataset.target).scrollIntoView({{behavior:'smooth', block:'start'}}); closeToc(); }});
  385. const search = byId('glossSearch');
  386. if (search) search.addEventListener('input', () => {{
  387. const q = search.value.trim().toLowerCase();
  388. document.querySelectorAll('.glossary-item').forEach(item => item.style.display = item.textContent.toLowerCase().includes(q) ? '' : 'none');
  389. }});
  390. const sclBtn = byId('sclCalcBtn');
  391. if (sclBtn) sclBtn.onclick = () => {{
  392. const sys = parseFloat(byId('sclSysClock').value) || 25;
  393. const tgt = parseFloat(byId('sclTarget').value) || 100;
  394. const cnt = Math.round((sys * 1000000) / (tgt * 1000) / 4 - 1);
  395. const actual = (sys * 1000000) / ((cnt + 1) * 4) / 1000;
  396. byId('sclCalcResult').textContent = `SCL_CNT_M = ${{cnt}}\\n实际 SCL ≈ ${{actual.toFixed(2)}} kHz\\n源码公式: SCL_CNT_M = SYS_CLOCK / SCL_CLOCK / 4 - 1`;
  397. }};
  398. const frameBtn = byId('i2cFrameBtn');
  399. if (frameBtn) frameBtn.onclick = () => {{
  400. const raw = byId('i2cAddr7').value.trim().replace(/^0x/i,'');
  401. const reg = byId('i2cReg').value.trim().replace(/^0x/i,'');
  402. let addr = parseInt(raw,16);
  403. if (addr > 0x7f) addr = addr >> 1;
  404. const wr = (addr << 1) & 0xfe;
  405. const rd = wr | 1;
  406. 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()}}`;
  407. }};
  408. const txText = [
  409. '顶层 wrreg_req 拉高一个时钟周期,control FSM 从 IDLE 进入 WR_REG。',
  410. 'cnt=0 发送 device_id,通常是地址写帧;ACK 失败先查地址、电源和上拉。',
  411. 'addr_mode 决定发送一个还是两个地址字节;addr_mode=0 发送原低 8 位。',
  412. '最后发送 wrdata,可组合 STO 生成停止条件。',
  413. 'ack <= ack | ack_o 汇总任意阶段 NACK;高电平是失败标志。'
  414. ];
  415. document.querySelectorAll('#transactionStepper button').forEach(btn => btn.onclick = () => byId('transactionStepText').textContent = txText[Number(btn.dataset.step)]);
  416. const debugText = {{
  417. nohw: 'No hardware:先查 USB 下载器、驱动、线缆和 TD 驱动安装,不要先改 RTL。',
  418. usb: 'USB Cable is connected:USB 侧可见,重点查目标板独立供电、VREF 接 VCC、GND 共地、JTAG 线序和 10P 1 脚。',
  419. crc: 'CRC / Chip ID:确认 bitstream 对应 EF2L45BG256B,文件未损坏,路径不是旧版本。',
  420. ok: '下载成功但无功能:继续验证复位、SCL/SDA 周期波形、地址 ACK、数据帧和当前 bit 是否只是 I2C demo。'
  421. }};
  422. document.querySelectorAll('#debugTree button').forEach(btn => btn.onclick = () => byId('debugPath').textContent = debugText[btn.dataset.node]);
  423. const pid = byId('pidScheduler');
  424. if (pid) {{
  425. for (let i=0; i<24; i++) {{
  426. const cell = document.createElement('div');
  427. cell.innerHTML = `<b>CH${{String(i).padStart(2,'0')}}</b><span>S_MULT → S_ACC → S_UPDATE</span>`;
  428. pid.appendChild(cell);
  429. }}
  430. }}
  431. """
  432. def render_chapter(data: dict[str, Any], chapter: dict[str, Any]) -> str:
  433. chapters = data["chapters"]
  434. glossary = data["glossary"]
  435. return f"""<!doctype html>
  436. <html lang="zh-CN">
  437. <head>
  438. <meta charset="utf-8">
  439. <meta name="viewport" content="width=device-width, initial-scale=1">
  440. <title>CPLD 第{chapter['id']}章 · {esc(chapter['title'])} · v1 重写版</title>
  441. <style>{css()}</style>
  442. </head>
  443. <body>
  444. <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>
  445. <div class="progress" id="progress"></div>
  446. {series_nav(chapter, chapters)}
  447. <div id="tocBackdrop" class="toc-backdrop"></div>
  448. {toc(chapter)}
  449. <div id="tooltip" class="tooltip"></div>
  450. <main>
  451. <section class="hero" id="top">
  452. <div class="hero-card">
  453. <p class="kicker">CPLD 全链路教学 · 源码化生成</p>
  454. <h1>{esc(chapter['title'])}</h1>
  455. <p class="lead">{esc(chapter['goal'])}</p>
  456. <p class="lead">读者定位:{esc(data['audience'])}。本页拒绝模板换标题,每个专节都回到 CPLD 工作区的源码、手册摘录、约束或排障现象。</p>
  457. </div>
  458. <div class="hero-panel">
  459. <p class="kicker">学习路径</p>
  460. {top_map(chapter, chapters)}
  461. </div>
  462. </section>
  463. {chapter_sections(chapter, glossary)}
  464. {chapter_synthesis(chapter)}
  465. <div id="tool">{interaction_html(chapter.get('interactive', ''), chapter)}</div>
  466. {glossary_html(glossary)}
  467. </main>
  468. <script>{js(glossary)}</script>
  469. </body>
  470. </html>
  471. """
  472. def generate(content: Path, output_dir: Path) -> list[Path]:
  473. data = load_content(content)
  474. output_dir.mkdir(parents=True, exist_ok=True)
  475. paths: list[Path] = []
  476. for chapter in data["chapters"]:
  477. html_text = render_chapter(data, chapter)
  478. path = output_dir / chapter["file"]
  479. path.write_text(html_text, encoding="utf-8", newline="\n")
  480. paths.append(path)
  481. return paths
  482. def main() -> int:
  483. parser = argparse.ArgumentParser(description=__doc__)
  484. parser.add_argument("--content", type=Path, default=DEFAULT_CONTENT)
  485. parser.add_argument("--output-dir", type=Path, required=True)
  486. parser.add_argument("--json", action="store_true", help="print generated file metadata as JSON")
  487. args = parser.parse_args()
  488. paths = generate(args.content, args.output_dir)
  489. payload = {"generated": [{"file": p.name, "bytes": p.stat().st_size} for p in paths]}
  490. if args.json:
  491. print(json.dumps(payload, ensure_ascii=False, indent=2))
  492. else:
  493. for path in paths:
  494. print(path)
  495. return 0
  496. if __name__ == "__main__":
  497. raise SystemExit(main())