pcb.py 12 KB

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