Skip to content
Edit this page

ictdesigntools.cabling.connections

Cables between ports, modelled as NetBox models them, and lane-by-lane tracing.

A Cable joins its A terminations to its B terminations (NetBox's a_terminations and b_terminations): front or rear ports of devices, named by device and port. It carries NetBox's cable fields (type, status, label, color, length, length_unit) and, optionally, the Assembly it is built from, whose profile and polarity say which lane on end A meets which lane on end B. A cable without an assembly joins its terminations in order, position to position, as a plain cable does in NetBox.

A Plant holds the devices (by name, each with its DeviceType and so its port templates and front-to-rear port mappings) and the cables. check finds what NetBox would refuse or a designer would want to know: unknown devices and ports, a port cabled twice, a connector that does not fit the port, an assembly whose connector count or positions differ from the ports'. trace follows one lane from a port position through cables and through each device's port mappings to where it ends, as NetBox's cable trace does; duplex traces a pair of lanes and says whether they cross, as a TIA-568 duplex channel must (transmit meets receive).

>>> from ictdesigntools.spaces.racks import device_type
>>> from ictdesigntools.cabling.assemblies import assembly
>>> panel = device_type("fiber-enclosure-1u")  # 48 LC front, 4 MPO-12 rear
>>> plant = Plant({"P1": panel, "P2": panel})
>>> trunk = plant.connect([("P1", "rear", "MPO 1")], [("P2", "rear", "MPO 1")],
...                       assembly("mpo12-trunk-om4-15m"))
>>> [str(s) for s in plant.trace(Termination("P1", "front", "1"))]
['P1 front 1', 'P1 rear MPO 1.1', 'P2 rear MPO 1.12', 'P2 front 12']
>>> plant.problems()
[]

Termination dataclass

Termination(device: str, side: str, port: str)

A port a cable ends on: a device, the port's side (front or rear) and its name. object_type gives NetBox's termination type.

Step dataclass

Step(
    port: Termination,
    position: int = 1,
    cable: int | None = None,
    _multi: bool = False,
)

One point of a trace: a port and a position on it (1 for a single-position port).

Cable dataclass

Cable(
    a_terminations: tuple[Termination, ...],
    b_terminations: tuple[Termination, ...],
    assembly: Assembly | None = None,
    type: str = "",
    status: str = "connected",
    label: str = "",
    color: str = "",
    length: float | None = None,
    length_unit: str = "m",
)

A cable between ports, with NetBox's cable field names.

cable_length property

cable_length: tuple[float, str] | None

The length and its unit: the cable's own, else its assembly's.

Plant

Plant(
    devices: dict[str, DeviceType],
    cables: list[Cable] | None = None,
)

Devices by name and the cables between their ports.

Source code in src/ictdesigntools/cabling/connections.py
def __init__(self, devices: dict[str, DeviceType], cables: list[Cable] | None = None):
    self.devices = dict(devices)
    self.cables: list[Cable] = list(cables or [])

from_racks classmethod

from_racks(racks: list[Rack]) -> Plant

The devices of some racks, by their labels, which must be unique (NetBox names devices uniquely within a site).

Source code in src/ictdesigntools/cabling/connections.py
@classmethod
def from_racks(cls, racks: list[Rack]) -> Plant:
    """The devices of some racks, by their labels, which must be unique (NetBox names
    devices uniquely within a site)."""
    devices: dict[str, DeviceType] = {}
    for rack in racks:
        for dev in rack.devices:
            if dev.label in devices:
                raise ValueError(f"Two devices are named “{dev.label}”: name them apart.")
            devices[dev.label] = dev.device_type
    return cls(devices)

connect

connect(
    a: list[tuple[str, str, str]],
    b: list[tuple[str, str, str]],
    assembly: Assembly | None = None,
    **fields,
) -> Cable

Add a cable from (device, side, port) triples on each end; returns it.

Source code in src/ictdesigntools/cabling/connections.py
def connect(self, a: list[tuple[str, str, str]], b: list[tuple[str, str, str]],
            assembly: Assembly | None = None, **fields) -> Cable:  # fmt: skip
    """Add a cable from (device, side, port) triples on each end; returns it."""
    cable = Cable(tuple(Termination(*t) for t in a), tuple(Termination(*t) for t in b),
                  assembly, **fields)  # fmt: skip
    self.cables.append(cable)
    return cable

template

template(t: Termination) -> PortTemplate | None

The port template a termination names, or None when there is no such port.

Source code in src/ictdesigntools/cabling/connections.py
def template(self, t: Termination) -> PortTemplate | None:
    """The port template a termination names, or None when there is no such port."""
    dt = self.devices.get(t.device)
    if dt is None:
        return None
    for tpl in dt.front_ports if t.side == "front" else dt.rear_ports:
        if t.port in tpl.names():
            return tpl
    return None

problems

problems() -> list[Problem]

Everything wrong with the cabling, cable by cable, in order.

Source code in src/ictdesigntools/cabling/connections.py
def problems(self) -> list[Problem]:
    """Everything wrong with the cabling, cable by cable, in order."""
    out: list[Problem] = []
    seen: dict[Termination, int] = {}
    for i, cable in enumerate(self.cables):
        for t in (*cable.a_terminations, *cable.b_terminations):
            if t in seen:
                out.append(Problem("double", f"{t} is cabled twice (cables {seen[t] + 1} "
                                   f"and {i + 1}).", (seen[t], i)))  # fmt: skip
            else:
                seen[t] = i
            if t.device not in self.devices:
                out.append(Problem("unknown", f"Cable {i + 1}: no device “{t.device}”.", (i,)))
            elif self.template(t) is None:
                out.append(Problem("unknown", f"Cable {i + 1}: {t.device} has no {t.side} "
                                   f"port “{t.port}”.", (i,)))  # fmt: skip
        out += self._fit(i, cable)
        if not cable.assembly and len(cable.a_terminations) != len(cable.b_terminations):
            out.append(Problem("count", f"Cable {i + 1} has {len(cable.a_terminations)} A and "
                               f"{len(cable.b_terminations)} B terminations: give it an "
                               "assembly whose profile says how they meet.", (i,)))  # fmt: skip
    return out

lanes

lanes(
    i: int,
) -> dict[tuple[Termination, int], tuple[Termination, int]]

Cable i's lanes both ways: (port, position) on one end to the same on the other. An assembly maps them by its profile and polarity; a plain cable joins its terminations in order, position to position.

Source code in src/ictdesigntools/cabling/connections.py
def lanes(self, i: int) -> dict[tuple[Termination, int], tuple[Termination, int]]:
    """Cable ``i``'s lanes both ways: (port, position) on one end to the same on the other.
    An assembly maps them by its profile and polarity; a plain cable joins its
    terminations in order, position to position."""
    cable = self.cables[i]
    out = {}
    if cable.assembly:
        ta, tb = cable.a_terminations, cable.b_terminations
        for lane in cable.assembly.lanes():
            (ca, pa), (cb, pb) = lane.a, lane.b
            if ca <= len(ta) and cb <= len(tb):
                a, b = (ta[ca - 1], pa), (tb[cb - 1], pb)
                out[a], out[b] = b, a
        return out
    for ta, tb in zip(cable.a_terminations, cable.b_terminations, strict=False):
        for k in range(1, min(self.positions(ta), self.positions(tb)) + 1):
            out[(ta, k)], out[(tb, k)] = (tb, k), (ta, k)
    return out

trace

trace(start: Termination, position: int = 1) -> list[Step]

One lane from a port position to its far end: across each cable at the port, then through the device to the port on its other face, until a port has no cable or a device has no mapping. Each step is a (port, position); a step a cable reached carries that cable's index.

Source code in src/ictdesigntools/cabling/connections.py
def trace(self, start: Termination, position: int = 1) -> list[Step]:
    """One lane from a port position to its far end: across each cable at the port, then
    through the device to the port on its other face, until a port has no cable or a
    device has no mapping. Each step is a (port, position); a step a cable reached
    carries that cable's index."""
    lanes = {}
    for i in range(len(self.cables)):
        lanes.update({k: (v, i) for k, v in self.lanes(i).items()})
    steps = [self._step(start, position, None)]
    here, seen = (start, position), {(start, position)}
    while True:
        # Leave this port by its cable, or through the device if the cable brought us here.
        if steps[-1].cable is None and here in lanes:
            (nxt, cable) = lanes[here]
        else:
            nxt, cable = self._through(*here), None
            if nxt is None:
                break
        if nxt in seen:
            raise ValueError(f"The trace from {start} loops at {nxt[0]}.")
        seen.add(nxt)
        steps.append(self._step(*nxt, cable))
        here = nxt
        if cable is None and here not in lanes:
            break
    return steps

duplex

duplex(
    tx: Termination,
    rx: Termination,
    tx_position: int = 1,
    rx_position: int = 1,
) -> tuple[Step, Step, bool]

Trace a duplex pair: where each lane ends, and whether they cross (the pair's first lane ending on the far pair's second, as TIA-568 needs so transmit meets receive). Crossing is judged by the far ends' order: port name, then position.

Source code in src/ictdesigntools/cabling/connections.py
def duplex(self, tx: Termination, rx: Termination, tx_position: int = 1,
           rx_position: int = 1) -> tuple[Step, Step, bool]:  # fmt: skip
    """Trace a duplex pair: where each lane ends, and whether they cross (the pair's first
    lane ending on the far pair's second, as TIA-568 needs so transmit meets receive).
    Crossing is judged by the far ends' order: port name, then position."""
    a, b = self.trace(tx, tx_position)[-1], self.trace(rx, rx_position)[-1]
    crossed = (_order(a), _order(b)) > (_order(b), _order(a))
    return a, b, crossed