pcb.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. """Extract footprint and pad metadata from a KiCad PCB."""
  2. from __future__ import annotations
  3. import math
  4. import re
  5. from dataclasses import dataclass, field
  6. from pathlib import Path
  7. from typing import TextIO
  8. from .sexpr import SExpr, iter_root_forms
  9. TOUCHPOINT_REFERENCE = re.compile(r"^(?:CON|J|PL|TP)\d+$")
  10. RESISTOR_REFERENCE = re.compile(r"^R\d+$")
  11. def _head(form: list[SExpr]) -> str:
  12. return str(form[0]) if form and isinstance(form[0], str) else ""
  13. def _children(form: list[SExpr], name: str) -> list[list[SExpr]]:
  14. return [item for item in form[1:] if isinstance(item, list) and _head(item) == name]
  15. def _child(form: list[SExpr], name: str) -> list[SExpr] | None:
  16. return next(iter(_children(form, name)), None)
  17. def _float(value: SExpr | None, default: float = 0.0) -> float:
  18. try:
  19. return float(str(value))
  20. except (TypeError, ValueError):
  21. return default
  22. def _values(form: list[SExpr] | None) -> list[str]:
  23. if form is None:
  24. return []
  25. return [str(item) for item in form[1:] if isinstance(item, str)]
  26. def _xy_angle(form: list[SExpr] | None) -> tuple[float, float, float]:
  27. values = _values(form)
  28. return (
  29. _float(values[0]) if values else 0.0,
  30. _float(values[1]) if len(values) > 1 else 0.0,
  31. _float(values[2]) if len(values) > 2 else 0.0,
  32. )
  33. def _normalize_angle(value: float) -> float:
  34. result = value % 360
  35. return 0.0 if math.isclose(result, 360.0) else result
  36. def _transform_point(
  37. local_x: float,
  38. local_y: float,
  39. origin_x: float,
  40. origin_y: float,
  41. rotation: float,
  42. ) -> tuple[float, float]:
  43. radians = math.radians(-rotation)
  44. cosine, sine = math.cos(radians), math.sin(radians)
  45. return (
  46. origin_x + local_x * cosine - local_y * sine,
  47. origin_y + local_x * sine + local_y * cosine,
  48. )
  49. @dataclass(frozen=True)
  50. class Pad:
  51. number: str
  52. pad_type: str
  53. shape: str
  54. x: float
  55. y: float
  56. width: float
  57. height: float
  58. rotation: float
  59. net: str | None
  60. layers: tuple[str, ...]
  61. drill_width: float
  62. drill_height: float
  63. mechanical: bool
  64. electrical: bool
  65. @dataclass
  66. class Footprint:
  67. reference: str
  68. component_value: str
  69. x: float
  70. y: float
  71. rotation: float
  72. side: str
  73. layer: str
  74. pads: list[Pad] = field(default_factory=list)
  75. bounds: dict[str, float] = field(default_factory=dict)
  76. def pad_by_number(self, number: str) -> Pad:
  77. for pad in self.pads:
  78. if pad.number == str(number):
  79. return pad
  80. raise KeyError(f"unknown pad {self.reference}.{number}")
  81. @dataclass
  82. class ParsedBoard:
  83. footprints: list[Footprint]
  84. footprint_count: int
  85. bounds: dict[str, float]
  86. def footprint_by_reference(self, reference: str) -> Footprint:
  87. for footprint in self.footprints:
  88. if footprint.reference == reference:
  89. return footprint
  90. raise KeyError(f"unknown footprint {reference}")
  91. def _reference(form: list[SExpr]) -> str | None:
  92. for prop in _children(form, "property"):
  93. values = _values(prop)
  94. if len(values) < 2 or values[0] != "Reference":
  95. continue
  96. reference = values[1].strip()
  97. if reference and reference != "${REFERENCE}":
  98. return reference
  99. for text in _children(form, "fp_text"):
  100. values = _values(text)
  101. if len(values) >= 2 and values[0] == "reference" and values[1] != "${REFERENCE}":
  102. return values[1]
  103. return None
  104. def _component_value(form: list[SExpr]) -> str:
  105. properties: dict[str, str] = {}
  106. for prop in _children(form, "property"):
  107. values = _values(prop)
  108. if len(values) >= 2 and values[1] and values[1] != "${REFERENCE}":
  109. properties.setdefault(values[0], values[1].strip())
  110. for name in ("Component Value", "Value"):
  111. if properties.get(name):
  112. return properties[name]
  113. if len(form) > 1 and isinstance(form[1], str):
  114. return form[1].strip()
  115. return ""
  116. def _drill_size(form: list[SExpr]) -> tuple[float, float]:
  117. drill = _child(form, "drill")
  118. if drill is None:
  119. return 0.0, 0.0
  120. numeric: list[float] = []
  121. for value in _values(drill):
  122. try:
  123. numeric.append(float(value))
  124. except ValueError:
  125. continue
  126. if not numeric:
  127. return 0.0, 0.0
  128. return numeric[0], numeric[1] if len(numeric) > 1 else numeric[0]
  129. def _parse_pad(
  130. form: list[SExpr],
  131. origin_x: float,
  132. origin_y: float,
  133. footprint_rotation: float,
  134. ) -> Pad:
  135. values = _values(form)
  136. number = values[0] if values else ""
  137. pad_type = values[1] if len(values) > 1 else "unknown"
  138. shape = values[2] if len(values) > 2 else "unknown"
  139. local_x, local_y, local_rotation = _xy_angle(_child(form, "at"))
  140. x, y = _transform_point(
  141. local_x,
  142. local_y,
  143. origin_x,
  144. origin_y,
  145. footprint_rotation,
  146. )
  147. size = _values(_child(form, "size"))
  148. width = _float(size[0]) if size else 0.0
  149. height = _float(size[1]) if len(size) > 1 else width
  150. drill_width, drill_height = _drill_size(form)
  151. net_values = _values(_child(form, "net"))
  152. net = net_values[-1] if net_values else None
  153. layers = tuple(_values(_child(form, "layers")))
  154. mechanical = pad_type == "np_thru_hole" or not number
  155. # KiCad pad "at" angle is relative to the footprint; emit board-absolute rotation.
  156. rotation = _normalize_angle(local_rotation + footprint_rotation)
  157. return Pad(
  158. number=number,
  159. pad_type=pad_type,
  160. shape=shape,
  161. x=x,
  162. y=y,
  163. width=width,
  164. height=height,
  165. rotation=rotation,
  166. net=net,
  167. layers=layers,
  168. drill_width=drill_width,
  169. drill_height=drill_height,
  170. mechanical=mechanical,
  171. electrical=not mechanical,
  172. )
  173. def _pad_bounds(pad: Pad) -> tuple[float, float, float, float]:
  174. width = max(pad.width, pad.drill_width, 0.5)
  175. height = max(pad.height, pad.drill_height, 0.5)
  176. radians = math.radians(pad.rotation)
  177. cosine, sine = abs(math.cos(radians)), abs(math.sin(radians))
  178. half_width = (width * cosine + height * sine) / 2
  179. half_height = (width * sine + height * cosine) / 2
  180. return (
  181. pad.x - half_width,
  182. pad.y - half_height,
  183. pad.x + half_width,
  184. pad.y + half_height,
  185. )
  186. def _footprint_bounds(pads: list[Pad], origin_x: float, origin_y: float) -> dict[str, float]:
  187. extents = [_pad_bounds(pad) for pad in pads]
  188. if not extents:
  189. extents = [(origin_x - 0.5, origin_y - 0.5, origin_x + 0.5, origin_y + 0.5)]
  190. minimum_x = min(item[0] for item in extents)
  191. minimum_y = min(item[1] for item in extents)
  192. maximum_x = max(item[2] for item in extents)
  193. maximum_y = max(item[3] for item in extents)
  194. return {
  195. "x": minimum_x,
  196. "y": minimum_y,
  197. "width": maximum_x - minimum_x,
  198. "height": maximum_y - minimum_y,
  199. }
  200. def _parse_footprint(form: list[SExpr]) -> Footprint | None:
  201. reference = _reference(form)
  202. if not reference:
  203. return None
  204. layer_values = _values(_child(form, "layer"))
  205. layer = layer_values[0] if layer_values else ""
  206. side = "back" if layer.startswith("B.") else "front"
  207. x, y, rotation = _xy_angle(_child(form, "at"))
  208. pads = [
  209. _parse_pad(pad, x, y, rotation)
  210. for pad in _children(form, "pad")
  211. ]
  212. return Footprint(
  213. reference=reference,
  214. component_value=_component_value(form),
  215. x=x,
  216. y=y,
  217. rotation=_normalize_angle(rotation),
  218. side=side,
  219. layer=layer,
  220. pads=pads,
  221. bounds=_footprint_bounds(pads, x, y),
  222. )
  223. def _point(form: list[SExpr] | None) -> tuple[float, float]:
  224. values = _values(form)
  225. return (
  226. _float(values[0]) if values else 0.0,
  227. _float(values[1]) if len(values) > 1 else 0.0,
  228. )
  229. def _arc_points(form: list[SExpr]) -> list[tuple[float, float]]:
  230. start = _point(_child(form, "start"))
  231. middle = _point(_child(form, "mid"))
  232. end = _point(_child(form, "end"))
  233. points = [start, middle, end]
  234. determinant = 2 * (
  235. start[0] * (middle[1] - end[1])
  236. + middle[0] * (end[1] - start[1])
  237. + end[0] * (start[1] - middle[1])
  238. )
  239. if math.isclose(determinant, 0.0, abs_tol=1e-12):
  240. return points
  241. start_sq = start[0] ** 2 + start[1] ** 2
  242. middle_sq = middle[0] ** 2 + middle[1] ** 2
  243. end_sq = end[0] ** 2 + end[1] ** 2
  244. center_x = (
  245. start_sq * (middle[1] - end[1])
  246. + middle_sq * (end[1] - start[1])
  247. + end_sq * (start[1] - middle[1])
  248. ) / determinant
  249. center_y = (
  250. start_sq * (end[0] - middle[0])
  251. + middle_sq * (start[0] - end[0])
  252. + end_sq * (middle[0] - start[0])
  253. ) / determinant
  254. radius = math.hypot(start[0] - center_x, start[1] - center_y)
  255. tau = math.tau
  256. start_angle = math.atan2(start[1] - center_y, start[0] - center_x) % tau
  257. middle_angle = math.atan2(middle[1] - center_y, middle[0] - center_x) % tau
  258. end_angle = math.atan2(end[1] - center_y, end[0] - center_x) % tau
  259. ccw_span = (end_angle - start_angle) % tau
  260. middle_ccw = (middle_angle - start_angle) % tau
  261. counter_clockwise = middle_ccw <= ccw_span + 1e-9
  262. def included(angle: float) -> bool:
  263. if counter_clockwise:
  264. return (angle - start_angle) % tau <= ccw_span + 1e-9
  265. clockwise_span = (start_angle - end_angle) % tau
  266. return (start_angle - angle) % tau <= clockwise_span + 1e-9
  267. for angle in (0.0, math.pi / 2, math.pi, 3 * math.pi / 2):
  268. if included(angle):
  269. points.append((center_x + radius * math.cos(angle), center_y + radius * math.sin(angle)))
  270. return points
  271. def _edge_points(form: list[SExpr]) -> list[tuple[float, float]]:
  272. layer = _values(_child(form, "layer"))
  273. if not layer or layer[0] != "Edge.Cuts":
  274. return []
  275. kind = _head(form)
  276. if kind == "gr_line":
  277. return [_point(_child(form, "start")), _point(_child(form, "end"))]
  278. if kind == "gr_rect":
  279. start = _point(_child(form, "start"))
  280. end = _point(_child(form, "end"))
  281. return [start, end, (start[0], end[1]), (end[0], start[1])]
  282. if kind == "gr_circle":
  283. center = _point(_child(form, "center"))
  284. end = _point(_child(form, "end"))
  285. radius = math.hypot(end[0] - center[0], end[1] - center[1])
  286. return [
  287. (center[0] - radius, center[1]),
  288. (center[0] + radius, center[1]),
  289. (center[0], center[1] - radius),
  290. (center[0], center[1] + radius),
  291. ]
  292. if kind == "gr_arc":
  293. return _arc_points(form)
  294. if kind in {"gr_poly", "gr_curve"}:
  295. points_form = _child(form, "pts")
  296. return [_point(item) for item in _children(points_form or [], "xy")]
  297. return []
  298. def _board_bounds(edge_points: list[tuple[float, float]], footprints: list[Footprint]) -> dict[str, float]:
  299. if edge_points:
  300. minimum_x = min(point[0] for point in edge_points)
  301. minimum_y = min(point[1] for point in edge_points)
  302. maximum_x = max(point[0] for point in edge_points)
  303. maximum_y = max(point[1] for point in edge_points)
  304. elif footprints:
  305. minimum_x = min(item.bounds["x"] for item in footprints)
  306. minimum_y = min(item.bounds["y"] for item in footprints)
  307. maximum_x = max(item.bounds["x"] + item.bounds["width"] for item in footprints)
  308. maximum_y = max(item.bounds["y"] + item.bounds["height"] for item in footprints)
  309. else:
  310. minimum_x = minimum_y = maximum_x = maximum_y = 0.0
  311. return {
  312. "x": minimum_x,
  313. "y": minimum_y,
  314. "width": maximum_x - minimum_x,
  315. "height": maximum_y - minimum_y,
  316. }
  317. def parse_kicad_pcb(source: Path | str | TextIO) -> ParsedBoard:
  318. footprints: list[Footprint] = []
  319. footprint_count = 0
  320. edge_points: list[tuple[float, float]] = []
  321. for form in iter_root_forms(source):
  322. kind = _head(form)
  323. if kind != "footprint":
  324. edge_points.extend(_edge_points(form))
  325. continue
  326. footprint_count += 1
  327. footprint = _parse_footprint(form)
  328. if footprint is not None:
  329. footprints.append(footprint)
  330. return ParsedBoard(
  331. footprints=footprints,
  332. footprint_count=footprint_count,
  333. bounds=_board_bounds(edge_points, footprints),
  334. )
  335. def select_touchpoints(board: ParsedBoard) -> list[Footprint]:
  336. return [footprint for footprint in board.footprints if TOUCHPOINT_REFERENCE.fullmatch(footprint.reference)]
  337. def select_resistors(board: ParsedBoard) -> list[Footprint]:
  338. """Discrete resistors only (`R` + digits). Excludes RN* arrays and other prefixes."""
  339. return [
  340. footprint
  341. for footprint in board.footprints
  342. if RESISTOR_REFERENCE.fullmatch(footprint.reference)
  343. ]