"""Serialize a `DrillFile` to XNC text.
XNC is a strict Excellon subset (spec 2021.11). The header is `M48`, the
unit, the tool table and `%`; the body is drill sections (`G05`, a tool, its
hits) and rout sections (`G00` to the start, tool down, the path, tool up),
and `M30` ends the file.
Attributes ride in standard comments (`; #@! TF...`), with Gerber X2
semantics: a tool is an aperture and a hole is an object. So this writer
carries the same attribute state machine `emit.py` does, which is easy to
overlook precisely because the attributes look like comments.
Tool diameters are finished sizes, after plating. Nothing here compensates
in either direction: the fabricator picks the bit.
"""
from __future__ import annotations
import logging
import math
from .contours import split_arc
from .model import (
CurveSeg,
DrillFile,
FileMeta,
Hit,
Seg,
Slot,
Tool,
escape_field,
)
from .units import grid, xnc_decimal
log = logging.getLogger(__name__)
MAX_TOOLS = 99
"""Tool numbers are two digits, 01 to 99 (3.4)."""
MAX_COMMENT = 255
"""A comment's content is at most 255 characters (3.1)."""
[docs]
class XncError(ValueError):
"""A drill file cannot be expressed in XNC."""
[docs]
def emit_xnc(file: DrillFile, meta: FileMeta) -> str:
"""The complete text of one XNC file, `M30` included.
Raises:
XncError: the file needs more distinct tools than XNC can number.
"""
tools = file.tools
if len(tools) > MAX_TOOLS:
raise XncError(
f"{len(tools)} distinct (diameter, function) tools in one XNC file; "
f"the format numbers at most {MAX_TOOLS}. Split the span or merge "
f"tool functions."
)
numbers = {tool: index + 1 for index, tool in enumerate(tools)}
lines = ["M48"]
lines += _header_attributes(file, meta)
if meta.compat.names:
lines.append(f"; Compatibility: {' '.join(meta.compat.names)}")
lines.append("METRIC")
current: dict[str, tuple[str, ...]] = {}
for tool in tools:
_diff(lines, "TA", current, dict(tool.attrs))
lines.append(f"T{numbers[tool]:02d}C{xnc_decimal(tool.diameter)}")
_diff(lines, "TA", current, {})
lines.append("%")
_Body(lines, numbers).run(file)
lines.append("M30")
return "\n".join(lines) + "\n"
def _header_attributes(file: DrillFile, meta: FileMeta) -> list[str]:
software = meta.software
project = meta.project
return [
_comment_attr(
"TF",
".GenerationSoftware",
(software.vendor, software.application, software.version),
),
_comment_attr("TF", ".CreationDate", (meta.creation_date,)),
_comment_attr(
"TF", ".ProjectId", (project.name, project.guid, project.revision)
),
_comment_attr("TF", ".SameCoordinates", ()),
_comment_attr("TF", ".FileFunction", tuple(file.function.render().split(","))),
]
def _comment_attr(kind: str, name: str, values: tuple[str, ...]) -> str:
"""One `; #@! ...` standard comment, capped at the comment length limit.
A long sanitized net name in a `TO.N` can exceed the cap. The value is
truncated with a warning rather than raising: the Gerber copper files
carry the full netlist, so the drill comment is the redundant copy and
losing an export over it would be the worse trade.
"""
body = "".join("," + escape_field(v) for v in values)
content = f" #@! {kind}{name}{body}"
if len(content) > MAX_COMMENT:
log.warning(
"XNC attribute %s%s exceeds the %d character comment limit; truncating",
kind,
name,
MAX_COMMENT,
)
content = content[:MAX_COMMENT]
return ";" + content
def _diff(
lines: list[str],
kind: str,
current: dict[str, tuple[str, ...]],
desired: dict[str, tuple[str, ...]],
) -> None:
"""Bring the attribute dictionary from `current` to `desired`."""
for name in list(current):
if current[name] != desired.get(name):
lines.append(_comment_attr("TD", name, ()))
del current[name]
for name, values in desired.items():
if current.get(name) != values:
lines.append(_comment_attr(kind, name, values))
current[name] = values
class _Body:
"""The modal drill/rout state while holes are written."""
def __init__(self, lines: list[str], numbers: dict[Tool, int]) -> None:
self.lines = lines
self.numbers = numbers
self.tool: Tool | None = None
self.drill_mode = False
self.attrs: dict[str, tuple[str, ...]] = {}
def run(self, file: DrillFile) -> None:
"""Hits first, then rout paths.
The grammar is a sequence of drill and rout sections, so grouping
them keeps the number of mode switches at one rather than one per
object, and a rout must be followed by `G05` before any further hit.
"""
for hit in file.hits:
self._hit(hit)
for slot in file.slots:
self._slot(slot)
_diff(self.lines, "TO", self.attrs, {})
def _select(self, tool: Tool) -> None:
if self.tool != tool:
self.lines.append(f"T{self.numbers[tool]:02d}")
self.tool = tool
def _hit(self, hit: Hit) -> None:
if not self.drill_mode:
self.lines.append("G05")
self.drill_mode = True
self.tool = None
self._select(hit.tool)
_diff(self.lines, "TO", self.attrs, dict(hit.attrs))
self.lines.append(f"X{xnc_decimal(hit.x)}Y{xnc_decimal(hit.y)}")
def _slot(self, slot: Slot) -> None:
"""One rout section: select the tool, `G00` to the start, `M15`, the
path, `M16`. The tool selection sits inside the section, which the
BNF is explicit about and a G00/M15/G01/M16 sketch leaves out."""
self.drill_mode = False
_diff(self.lines, "TO", self.attrs, dict(slot.attrs))
self.lines.append(f"T{self.numbers[slot.tool]:02d}")
self.tool = slot.tool
here = (grid(slot.start[0]), grid(slot.start[1]))
self.lines.append(f"G00X{xnc_decimal(here[0])}Y{xnc_decimal(here[1])}")
self.lines.append("M15")
for segment in slot.segments:
end = (grid(segment.x), grid(segment.y))
if isinstance(segment, Seg):
self.lines.append(f"G01X{xnc_decimal(end[0])}Y{xnc_decimal(end[1])}")
here = end
else:
here = self._rout_arc(here, end, segment)
self.lines.append("M16")
def _rout_arc(
self, start: tuple[float, float], end: tuple[float, float], segment: CurveSeg
) -> tuple[float, float]:
"""A `G02`/`G03` rout, split so every piece spans at most 180
degrees, which XNC requires. The command carries a radius rather
than a center, so the center only has to survive the split.
Raises:
XncError: the radius is degenerate.
"""
center = (grid(segment.cx), grid(segment.cy))
radius = math.hypot(start[0] - center[0], start[1] - center[1])
if radius <= 0:
raise XncError(f"rout arc with zero radius at {start}")
code = "G03" if segment.ccw else "G02"
for point in [*split_arc(start, end, center, segment.ccw), end]:
self.lines.append(
f"{code}X{xnc_decimal(point[0])}Y{xnc_decimal(point[1])}A{xnc_decimal(radius)}"
)
return end