1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
|
#!/usr/bin/env python3
"""One net-class table for every board in a repo: modules, templates, base boards.
python3 tools/netclasses.py PROJECT.kicad_pro [...] write the table
python3 tools/netclasses.py --check PROJECT.kicad_pro [...] report drift, exit 1 if any
python3 tools/netclasses.py --table my.json PROJECT.kicad_pro
The table is netclasses.json at the repo root (see kicad_paths.ROOT) when it exists, else
the generic default below.
Writes net_settings.classes, net_settings.netclass_patterns and the track-width, via and
diff-pair palettes. All other project settings stay as they are. Close the project in
KiCad first: an open editor writes its own copy back when it saves.
Patterns are sheet-independent (*/NET), so the same list works in a module's test
project and on a base board where the module sits under another sheet name. A pattern
that matches no net does nothing, so module-specific classes can live here too; their
names are then reserved for all modules. Lower priority numbers win when several
patterns match one net.
Class widths are routing defaults, not minimums: short narrower escapes stay legal.
Rationale and sizing: knowledge/topics/netclasses.md
"""
import argparse
import copy
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from kicad_paths import ROOT # noqa: E402
# Generic default table. A netclasses.json at the repo root (or --table FILE) replaces it:
# {"clearance": 0.2, "via": 0.6, "drill": 0.3, "default_width": 0.2,
# "track_widths": [0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0],
# "classes": {"Power": [0.5, null, null, ["+3V3", "*/VBUS"]], ...}}
# Each class is [track width, diff pair width, diff pair gap, patterns], in priority order.
CLEARANCE, VIA, DRILL = 0.2, 0.6, 0.3
CLASSES = {
"Ethernet": (0.25, 0.25, 0.2, ["*/ETH_TX?", "*/ETH_RX?"]),
"USB": (0.25, 0.25, 0.2, ["*/USB_DP", "*/USB_DN"]),
"Power": (0.5, None, None, ["+3V3", "+5V", "*/3V3", "*/VBUS", "Net-(*-SW)"]),
"Ground": (0.4, None, None, ["GND"]),
}
DEFAULT_WIDTH = 0.2
TRACK_WIDTHS = [0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0]
def load_table(path):
"""Replace the module's table with a JSON file's (see the comment above CLASSES)."""
global CLEARANCE, VIA, DRILL, DEFAULT_WIDTH, TRACK_WIDTHS, CLASSES, VIAS, DIFF_PAIRS
with open(path) as fh:
d = json.load(fh)
CLEARANCE = d.get("clearance", CLEARANCE)
VIA, DRILL = d.get("via", VIA), d.get("drill", DRILL)
DEFAULT_WIDTH = d.get("default_width", DEFAULT_WIDTH)
TRACK_WIDTHS = d.get("track_widths", TRACK_WIDTHS)
CLASSES = {k: tuple(v) for k, v in d["classes"].items()}
_palettes()
BASE.update(clearance=CLEARANCE, track_width=DEFAULT_WIDTH, via_diameter=VIA, via_drill=DRILL)
def _palettes():
global VIAS, DIFF_PAIRS
VIAS = [{"diameter": 0, "drill": 0}, {"diameter": VIA, "drill": DRILL}]
pairs = sorted({(dw, g) for _, dw, g, _ in CLASSES.values() if dw})
DIFF_PAIRS = [{"gap": 0, "via_gap": 0, "width": 0}] + [{"gap": g, "via_gap": 0.25, "width": w} for w, g in pairs]
_palettes()
BASE = {
"bus_width": 12, "clearance": CLEARANCE, "diff_pair_gap": 0.25, "diff_pair_via_gap": 0.25,
"diff_pair_width": 0.2, "line_style": 0, "microvia_diameter": 0.3, "microvia_drill": 0.1,
"name": "Default", "pcb_color": "rgba(0, 0, 0, 0.000)", "priority": 2147483647,
"schematic_color": "rgba(0, 0, 0, 0.000)", "track_width": DEFAULT_WIDTH, "tuning_profile": "",
"via_diameter": VIA, "via_drill": DRILL, "wire_width": 6,
}
if os.path.exists(os.path.join(ROOT, "netclasses.json")):
load_table(os.path.join(ROOT, "netclasses.json"))
def table():
classes, patterns = [copy.deepcopy(BASE)], []
for prio, (name, (width, dp_width, dp_gap, pats)) in enumerate(CLASSES.items()):
c = copy.deepcopy(BASE)
c.update(name=name, priority=prio, track_width=width)
if dp_width:
c.update(diff_pair_width=dp_width, diff_pair_gap=dp_gap)
classes.append(c)
patterns += [{"netclass": name, "pattern": p} for p in pats]
return classes, patterns
def apply(project):
"""Write the shared table into a parsed .kicad_pro (dict), in place."""
classes, patterns = table()
project["net_settings"]["classes"] = classes
project["net_settings"]["netclass_patterns"] = patterns
ds = project["board"]["design_settings"]
ds["track_widths"], ds["via_dimensions"], ds["diff_pair_dimensions"] = [0] + [w for w in TRACK_WIDTHS if w], copy.deepcopy(VIAS), copy.deepcopy(DIFF_PAIRS)
return project
def drift(project):
want = apply(copy.deepcopy(project))
out = []
for path in (("net_settings", "classes"), ("net_settings", "netclass_patterns"), ("board", "design_settings", "track_widths"),
("board", "design_settings", "via_dimensions"), ("board", "design_settings", "diff_pair_dimensions")):
a, b = project, want
for k in path:
a, b = a.get(k), b.get(k)
if path[-1] == "classes": # KiCad saves the classes sorted by name; priority carries the order
a, b = (sorted(x or [], key=lambda c: c["name"]) for x in (a, b))
if a != b:
out.append("/".join(path))
return out
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("projects", nargs="+")
ap.add_argument("--check", action="store_true", help="only report projects that differ from the table")
ap.add_argument("--table", help="net-class table (JSON); default: netclasses.json at the repo root if present")
a = ap.parse_args()
if a.table:
load_table(a.table)
bad = 0
for p in a.projects:
with open(p) as fh:
d = json.load(fh)
diff = drift(d)
if a.check:
print("%s: %s" % (p, "differs in " + ", ".join(diff) if diff else "ok"))
bad += bool(diff)
elif diff:
with open(p, "w") as fh:
fh.write(json.dumps(apply(d), indent=2) + "\n")
print("%s: updated %s" % (p, ", ".join(diff)))
else:
print("%s: already up to date" % p)
sys.exit(1 if bad else 0)
if __name__ == "__main__":
main()
|