MAC 주소와 이더넷 프레임 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# MAC 주소와 이더넷 프레임 문서의 그림을 만든다: 65_ethernet-frame_fig1.svg, fig2.svg
# fig1 프레임의 칸 배치(비트 수와 바이트 수). 칸 폭은 실제 비율이 아니고 몸통만 늘였다 줄였다 하는 칸으로 그렸다.
# fig2 주소 08:00:2b:e4:b1:02의 첫 바이트가 선에 나가는 순서(가장 낮은 비트부터)
# 실행: ~/.venvs/vault-plots/bin/python -I 65_ethernet-frame_plot.py  (matplotlib, numpy 필요)
import os

import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.patches import Rectangle

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "65_ethernet-frame"
INK = "#888888"
C = ["#3b82c4", "#d9622b", "#3a9a5b", "#9b59b6", "#c49a1b"]
BLUE, ORANGE, GREEN, PURPLE, GOLD = C
_fonts = {f.name for f in font_manager.fontManager.ttflist}
FONT = next((n for n in ["Apple SD Gothic Neo", "NanumGothic", "Noto Sans CJK KR"] if n in _fonts), "DejaVu Sans")
plt.rcParams.update({
    "font.family": FONT, "font.size": 10.5, "axes.unicode_minus": False, "svg.fonttype": "path",
    "svg.hashsalt": PREFIX, "text.color": INK,
    "axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
})

FIELDS = [  # (이름, 비트, 그림 폭, 색, 설명)
    ("프리앰블", 64, 1.5, INK, "준비 신호"),
    ("목적지 주소", 48, 1.4, BLUE, "받을 어댑터"),
    ("출발지 주소", 48, 1.4, BLUE, "보낸 어댑터"),
    ("종류", 16, 1.1, GREEN, "길이·종류"),
    ("몸통", None, 2.4, GOLD, "46~1500바이트"),
    ("CRC", 32, 0.9, ORANGE, "오류 검출"),
]


def save(fig, k):
    fig.savefig(os.path.join(HERE, f"{PREFIX}_fig{k}.svg"), bbox_inches="tight", metadata={"Date": None})
    if os.environ.get("PREVIEW_DIR"):
        fig.savefig(os.path.join(os.environ["PREVIEW_DIR"], f"{PREFIX}_fig{k}.png"), bbox_inches="tight", dpi=110,
                    facecolor="white")
    plt.close(fig)


def fig1():
    fig, ax = plt.subplots(figsize=(7.8, 2.6))
    x = 0.0
    edges = {}
    for name, bits, w, col, note in FIELDS:
        ax.add_patch(Rectangle((x, 0), w, 1, facecolor=col, alpha=0.22, edgecolor=col, lw=1.3))
        ax.text(x + w / 2, 0.62, name, ha="center", va="center", fontsize=10.5, color=col)
        ax.text(x + w / 2, 0.28, note, ha="center", va="center", fontsize=9.5)
        top = f"{bits}비트" if bits else "가변"
        ax.text(x + w / 2, 1.18, top, ha="center", va="center", fontsize=10)
        edges[name] = (x, x + w)
        x += w
    # 최소 64바이트 = 목적지부터 CRC까지
    a, b = edges["목적지 주소"][0], edges["CRC"][1]
    ax.annotate("", xy=(a, -0.35), xytext=(b, -0.35), arrowprops=dict(arrowstyle="<->", color=PURPLE, lw=1.2))
    ax.text((a + b) / 2, -0.62, "목적지 주소부터 CRC까지가 프레임 길이: 최소 64바이트(512비트), 최대 1518바이트",
            ha="center", fontsize=10, color=PURPLE)
    ax.annotate("", xy=(x, 1.55), xytext=(0, 1.55), arrowprops=dict(arrowstyle="-|>", color=INK, lw=1))
    ax.text(0, 1.72, "선에 나가는 순서 →", fontsize=10)
    ax.set_xlim(-0.1, x + 0.1)
    ax.set_ylim(-0.85, 1.95)
    ax.axis("off")
    save(fig, 1)
    return x


def fig2():
    first_byte = 0x08
    bits_msb = [(first_byte >> i) & 1 for i in range(7, -1, -1)]   # 적는 순서: 높은 비트부터
    wire = [(first_byte >> i) & 1 for i in range(8)]               # 선에 나가는 순서: 낮은 비트부터
    fig, ax = plt.subplots(figsize=(7.0, 2.4))
    for row, (label, seq) in enumerate([("16진수로 적은 순서 (08)", bits_msb), ("선에 나가는 순서", wire)]):
        y = 1.4 - row * 1.2
        ax.text(-0.2, y + 0.3, label, ha="right", va="center", fontsize=10)
        for i, b in enumerate(seq):
            hot = (row == 0 and i == 7) or (row == 1 and i == 0)
            col = GREEN if hot else INK
            ax.add_patch(Rectangle((i * 0.6, y), 0.55, 0.6, facecolor=col if hot else "none", alpha=0.25 if hot else 1,
                                   edgecolor=col, lw=1.2))
            ax.text(i * 0.6 + 0.275, y + 0.3, str(b), ha="center", va="center", fontsize=11, color=col)
    ax.annotate("", xy=(0.275, 1.0), xytext=(7 * 0.6 + 0.275, 1.4),
                arrowprops=dict(arrowstyle="-|>", color=GREEN, lw=1.2))
    ax.text(5.0, 0.5, "첫 비트 = 0\n→ 그룹 주소가 아니다", fontsize=10, color=GREEN)
    ax.set_xlim(-3.6, 6.6)
    ax.set_ylim(0.0, 2.2)
    ax.axis("off")
    save(fig, 2)
    return wire


if __name__ == "__main__":
    fig1()
    bits = {n: b for n, b, *_ in FIELDS}
    assert bits["목적지 주소"] + bits["출발지 주소"] + bits["종류"] + 46 * 8 + bits["CRC"] == 512
    assert (bits["목적지 주소"] + bits["출발지 주소"] + bits["종류"]) // 8 == 14
    wire = fig2()
    assert wire[0] == 0 and wire[3] == 1                       # 0x08 = 0000 1000
    print("ALL CHECKS PASSED")