#!/usr/bin/env python3
"""
edgetx_channels.py - draw an EdgeTX model's channel dependency graph as a
draw.io diagram that fits one A4 page.
python edgetx_channels.py MODEL.yml [REFERENCE.xlsx] [-o OUT.drawio]
[--orientation auto|landscape|portrait]
[--preview OUT.png] [--list-issues]
MODEL.yml EdgeTX model exported as YAML (required, primary source).
REFERENCE.xlsx Optional workbook. Used only for labels: a short description
under each channel name, the colour groups (from its upper-case
section headings) and flight-mode names missing from the YAML.
Each channel that has mixer lines (or is used by another channel) is a node.
Each node lists its mixer lines. An arrow runs from a channel to the mixer
line that uses it, either as the mixer source (solid) or as a diff/expo
curve parameter (dashed blue). Links that would form a cycle are drawn red.
Requires: pip install pyyaml openpyxl
Optional: pip install pillow (accurate text fitting, and --preview)
"""
import argparse
import itertools
import math
import os
import re
import sys
import warnings
from collections import Counter
from xml.sax.saxutils import escape
import yaml
try:
import openpyxl
except ImportError:
openpyxl = None
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError:
ImageFont = None
# --------------------------------------------------------------------------
# constants
# --------------------------------------------------------------------------
A4_LAND = (1169, 827) # draw.io A4 at 100 %
FS_ROW, FS_HEAD, FS_SUB = 8, 9, 8
LINE_H = 10 # px per text line in a mixer row
PAD_X = 14 # horizontal padding inside a row
GAP_Y = 12 # vertical gap between nodes
DUMMY_H = 8 # vertical space reserved for a passing edge
TITLE_H, LEGEND_H, MARGIN = 52, 84, 20
JUMP = 5 # draw.io line-jump (arc) size; an arc spans about +/- JUMP px
LANE_M, LANE_SP = 12, 12 # clearance of a lane from a box edge / spacing between lanes (px)
NEAR = JUMP + 3.0 # a line-jump closer than this to a bend or box edge looks cramped
PALETTE = [("#dae8fc", "#6c8ebf"), ("#d5e8d4", "#82b366"), ("#fff2cc", "#d6b656"),
("#e1d5e7", "#9673a6"), ("#ffe6cc", "#d79b00"), ("#f8cecc", "#b85450"),
("#f5f5f5", "#999999")]
MODE_COL = {"REPL": "#c55a11", "MUL": "#7030a0"} # font colours for REPL / MULT mixers
TRIMS = {"T1": "TrmR", "T2": "TrmE", "T3": "TrmT", "T4": "TrmA"}
FUNCS = {1: "x>0", 2: "x<0", 3: "|x|", 4: "f>0", 5: "f<0", 6: "|f|"}
KNOWN_SRC = re.compile(r"(MAX|MIN|none|Rud|Ele|Thr|Ail|S[A-H]|S[1-9]|P[1-9]|[LR]S|"
r"Trim[A-Za-z]+|ON|OFF|TX[A-Za-z]*|Batt|Time|Timer\d|Tmr\d|cyc[1-3]|"
r"gv\(\d+\)|I\d+|ch\(\d+\)|T\d)")
# --------------------------------------------------------------------------
# text measurement (Pillow if available, otherwise a cautious estimate)
# --------------------------------------------------------------------------
class Metrics:
FONTS = {
False: ["C:/Windows/Fonts/arial.ttf",
"/System/Library/Fonts/Supplemental/Arial.ttf",
"/Library/Fonts/Arial.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"],
True: ["C:/Windows/Fonts/arialbd.ttf",
"/System/Library/Fonts/Supplemental/Arial Bold.ttf",
"/Library/Fonts/Arial Bold.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]}
def __init__(self):
self.font = {}
if ImageFont:
for bold, paths in self.FONTS.items():
for p in paths:
if os.path.exists(p):
try:
self.font[bold] = ImageFont.truetype(p, 40)
break
except OSError:
pass
def width(self, s, size=FS_ROW, bold=False):
f = self.font.get(bold)
if f:
return f.getlength(s) * size / 40.0
return len(s) * size * (0.60 if bold else 0.55) # conservative
def fit(self, s, maxw, size=FS_ROW, bold=False):
if self.width(s, size, bold) <= maxw:
return s
while s and self.width(s + "…", size, bold) > maxw:
s = s[:-1]
return s.rstrip() + "…"
def wrap(self, items, maxw, sep=" · ", size=FS_ROW):
lines, cur = [], ""
for it in items:
trial = it if not cur else cur + sep + it
if cur and self.width(trial, size) > maxw:
lines.append(cur)
cur = it
else:
cur = trial
if cur:
lines.append(cur)
return lines
# --------------------------------------------------------------------------
# reading the files
# --------------------------------------------------------------------------
def load_model(path):
text = open(path, encoding="utf-8").read()
# flight-mode masks such as 011010111 would be read as octal numbers
text = re.sub(r"^(\s*flightModes:\s*)([01]+)\s*$", r'\1"\2"', text, flags=re.M)
return yaml.safe_load(text)
def as_dict(x):
if not x:
return {}
return dict(enumerate(x)) if isinstance(x, list) else x
def read_workbook(path, issues):
"""Return dict(desc={ch: text}, name={ch: name}, group={ch: heading},
group_order=[headings], fm={n: name})."""
out = dict(desc={}, name={}, group={}, group_order=[], fm={})
if not path:
return out
if openpyxl is None:
sys.exit("openpyxl is needed to read the workbook: pip install openpyxl")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
wb = openpyxl.load_workbook(path, data_only=True)
ch_re = re.compile(r"^CH\s*0*(\d+)\s*[::]\s*([A-Za-z0-9_\-]+)")
weightish = re.compile(r"^[+\-]?(\d|GV|!)")
for ws in wb.worksheets:
rows = []
for r in ws.iter_rows():
cells = [(c.column, str(c.value).strip()) for c in r
if c.value is not None and str(c.value).strip()]
rows.append(cells)
for cells in rows: # flight-mode names
for _, v in cells:
m = re.match(r"^FM(\d+)\s*:\s*(\w+)", v)
if m:
out["fm"].setdefault(int(m[1]), m[2])
found = [] # (col, ch, name, next text)
for ri, cells in enumerate(rows):
for k, (col, v) in enumerate(cells):
m = ch_re.match(v)
if m:
nxt = next((t for _, t in cells[k + 1:]), "")
found.append((ri, col, int(m[1]), m[2], nxt))
if not found:
continue
descriptive = Counter(f[1] for f in found if " " in f[4] and len(f[4]) > 8)
col = descriptive.most_common(1)[0][0] if descriptive else min(f[1] for f in found)
defs = {f[0]: f for f in found if f[1] == col and not weightish.match(f[4] or "-")}
heading = None
for ri, cells in enumerate(rows):
if len(cells) == 1 and cells[0][1].isupper() and 3 < len(cells[0][1]) <= 30 \
and not ch_re.match(cells[0][1]):
heading = cells[0][1].capitalize()
if heading not in out["group_order"]:
out["group_order"].append(heading)
if ri in defs:
_, _, ch, name, nxt = defs[ri]
out["name"].setdefault(ch, name)
out["desc"].setdefault(ch, nxt)
if heading:
out["group"].setdefault(ch, heading)
if not out["name"]:
issues.append("workbook: no 'CHn:Name' channel definitions found; labels skipped")
return out
def short_label(desc):
if not desc:
return ""
cut = re.split(r"\.\s|\s=\s|\s[-–]\s|\s\(|;|:\s|\n", desc, maxsplit=1)[0]
return cut.strip().rstrip(".")
# --------------------------------------------------------------------------
# decoding mixer lines
# --------------------------------------------------------------------------
class Model:
def __init__(self, d, xl, issues):
self.d, self.xl, self.issues = d, xl, issues
self.lim = {int(k) + 1: (v or {}).get("name", "") or ""
for k, v in as_dict(d.get("limitData")).items()}
self.inp = {int(k): (v or {}).get("val", "") for k, v in as_dict(d.get("inputNames")).items()}
self.gv = {int(k): (v or {}).get("name", "") for k, v in as_dict(d.get("gvars")).items()}
self.cv = {int(k): (v or {}).get("name", "") for k, v in as_dict(d.get("curves")).items()}
self.fm = {}
for k, v in as_dict(d.get("flightModeData")).items():
self.fm[int(k)] = (v or {}).get("name") or xl["fm"].get(int(k)) or f"FM{k}"
def chname(self, n):
name = self.lim.get(n) or self.xl["name"].get(n) or ""
return f"CH{n}:{name}" if name else f"CH{n}"
def gvname(self, i):
n = self.gv.get(i)
return f"GV{i + 1}:{n}" if n else f"GV{i + 1}"
def source(self, s):
"""-> (text, channel number or None)"""
s = str(s)
neg = "-" if s.startswith("!") else ""
t = s.lstrip("!")
m = re.fullmatch(r"ch\((\d+)\)", t)
if m:
return neg + self.chname(int(m[1]) + 1), int(m[1]) + 1
m = re.fullmatch(r"I(\d+)", t)
if m:
n = self.inp.get(int(m[1]))
return neg + (f"I{int(m[1]) + 1}:{n}" if n else f"I{int(m[1]) + 1}"), None
m = re.fullmatch(r"gv\((\d+)\)", t)
if m:
return neg + self.gvname(int(m[1])), None
if t in TRIMS:
return neg + TRIMS[t], None
if not KNOWN_SRC.fullmatch(t):
self.issues.append(f"source '{s}' not recognised - shown as written")
return s, None
def value(self, v):
"""weight / offset / curve parameter -> (text, channel number or None)"""
if isinstance(v, (int, float)):
return f"{v:+g}%", None
v = str(v)
m = re.fullmatch(r"(!?)gv\((\d+)\)", v)
if m:
return ("-" if m[1] else "+") + self.gvname(int(m[2])), None
m = re.fullmatch(r"(!?)ch\((\d+)\)", v)
if m:
return ("-" if m[1] else "") + self.chname(int(m[2]) + 1), int(m[2]) + 1
self.issues.append(f"value '{v}' not recognised - shown as written")
return v, None
def curve(self, c):
"""-> (modifier text or '', channel number or None)"""
t, v = c.get("type", 0), c.get("value", 0)
if t in (0, 1): # diff / expo
if v == 0:
return "", None
txt, ch = self.value(v)
return ("diff " if t == 0 else "expo ") + txt.lstrip("+"), ch
if t == 2:
if v not in FUNCS:
self.issues.append(f"function curve {v} not recognised")
return "func " + FUNCS.get(v, str(v)), None
if t == 3:
n = abs(v)
nm = self.cv.get(n - 1, "")
return ("-" if v < 0 else "") + f"CV{n}" + (f":{nm}" if nm else ""), None
self.issues.append(f"curve type {t} not recognised")
return "", None
def flight_modes(self, mask):
mask = str(mask)
if not re.fullmatch(r"[01]+", mask):
self.issues.append(f"flight-mode mask '{mask}' not recognised")
return ""
en = [i for i, c in enumerate(mask) if c == "0"]
dis = [i for i, c in enumerate(mask) if c == "1"]
nm = lambda ids: ",".join(self.fm.get(i, f"FM{i}") for i in ids)
if not dis:
return ""
if not en:
return "FM none"
return "FM " + nm(en) if len(en) <= len(dis) else "FM not " + nm(dis)
def rows(self):
"""-> {channel: [row dict]} ; row = l1, mods, src, curve"""
data = {}
for m in self.d.get("mixData") or []:
ch = int(m["destCh"]) + 1
pre = {"REPL": "REPL ", "MUL": "MULT "}.get(m.get("mltpx", "ADD"), "")
if m.get("mltpx", "ADD") not in ("ADD", "REPL", "MUL"):
self.issues.append(f"mixer type '{m.get('mltpx')}' not recognised")
stxt, sch = self.source(m.get("srcRaw", ""))
wtxt, _ = self.value(m.get("weight", 100))
mods = []
ctxt, cch = self.curve(m.get("curve") or {})
if ctxt:
mods.append(ctxt)
if m.get("offset", 0) not in (0, "0"):
mods.append("off " + self.value(m["offset"])[0])
fmt = self.flight_modes(m.get("flightModes", "000000000"))
if fmt:
mods.append(fmt)
if m.get("swtch", "NONE") not in ("NONE", None):
mods.append("sw " + str(m["swtch"]))
data.setdefault(ch, []).append(
dict(l1=f"{pre}{stxt} {wtxt}", mods=mods, src=sch, curve=cch,
mode=m.get("mltpx", "ADD")))
return data
# --------------------------------------------------------------------------
# graph: cycles, layers, ordering, vertical placement
# --------------------------------------------------------------------------
def find_back_edges(nodes, adj):
state, back = {}, set()
def dfs(u):
state[u] = 1
for v in sorted(adj.get(u, ())):
if state.get(v) == 1:
back.add((u, v))
elif v not in state:
dfs(v)
state[u] = 2
for n in sorted(nodes):
if n not in state:
dfs(n)
return back
def assign_layers(nodes, fwd):
succ = {n: set() for n in nodes}
pred = {n: set() for n in nodes}
for a, b in fwd:
succ[a].add(b)
pred[b].add(a)
indeg = {n: len(pred[n]) for n in nodes}
topo, queue = [], sorted(n for n in nodes if indeg[n] == 0)
while queue:
n = queue.pop(0)
topo.append(n)
for s in sorted(succ[n]):
indeg[s] -= 1
if indeg[s] == 0:
queue.append(s)
lay = {n: 0 for n in nodes}
for n in topo: # longest path from the sources
for s in succ[n]:
lay[s] = max(lay[s], lay[n] + 1)
for n in reversed(topo): # pull towards consumers (ALAP);
if succ[n]: # terminal channels keep their depth
lay[n] = min(lay[s] for s in succ[n]) - 1
return lay
def order_and_place(nodes, lay, chains, height):
"""chains: list of node-id sequences, one per forward edge (dummies inside).
Returns (layers, y_top) where y_top[item] is the item's top edge."""
nlay = max(lay.values()) + 1 if lay else 1
layer_of = dict(lay)
for seq in chains:
for k, it in enumerate(seq[1:-1], 1):
layer_of[it] = lay[seq[0]] + k
key = lambda n: n if isinstance(n, int) else n[1]
layers = [sorted([n for n, l in layer_of.items() if l == k], key=key) for k in range(nlay)]
links = {(u, v) for seq in chains for u, v in zip(seq, seq[1:])}
pred = {n: [u for u, v in links if v == n] for n in layer_of}
succ = {n: [v for u, v in links if u == n] for n in layer_of}
def pos():
return {n: i for L in layers for i, n in enumerate(L)}
def crossings():
p, c = pos(), 0
for k in range(nlay - 1):
es = [(p[u], p[v]) for u, v in links if layer_of[u] == k]
for i in range(len(es)):
for j in range(i + 1, len(es)):
if (es[i][0] - es[j][0]) * (es[i][1] - es[j][1]) < 0:
c += 1
return c
best, bestc = [list(L) for L in layers], crossings()
for it in range(10):
down = it % 2 == 0
for k in (range(1, nlay) if down else range(nlay - 2, -1, -1)):
p, nb = pos(), (pred if down else succ)
bary = lambda n: (sum(p[m] for m in nb[n]) / len(nb[n])) if nb[n] else p[n]
layers[k].sort(key=lambda n: (bary(n), p[n]))
c = crossings()
if c < bestc:
best, bestc = [list(L) for L in layers], c
layers = best
H = {n: (height[n] if isinstance(n, int) else DUMMY_H) for n in layer_of}
colh = [sum(H[n] for n in L) + GAP_Y * max(0, len(L) - 1) for L in layers]
top = {}
for L, h in zip(layers, colh):
t = (max(colh) - h) / 2
for n in L:
top[n] = t
t += H[n] + GAP_Y
for it in range(8): # relax towards neighbours' centres
down = it % 2 == 0
for k in (range(1, nlay) if down else range(nlay - 2, -1, -1)):
nb, prev = (pred if down else succ), -1e9
for n in layers[k]:
cs = [top[m] + H[m] / 2 for m in nb[n]]
want = sum(cs) / len(cs) - H[n] / 2 if cs else top[n]
top[n] = max(want, prev + GAP_Y)
prev = top[n] + H[n]
lim = max(colh) # never grow taller than the tallest column
for n in reversed(layers[k]):
top[n] = min(top[n], lim - H[n])
lim = top[n] - GAP_Y
lo = min(top.values()) if top else 0
for n in top:
top[n] -= lo
return layers, top, layer_of, H
def lane_order(ks):
"""Left-to-right order of the vertical lanes in one gap that gives the fewest crossings.
ks: key -> dict(L=y where the line arrives from the left, R=set of y where lines leave to the right)."""
names = sorted(ks, key=lambda k: (ks[k]["L"] + sum(ks[k]["R"]) / len(ks[k]["R"])) / 2)
span = {k: (min(ks[k]["R"] | {ks[k]["L"]}), max(ks[k]["R"] | {ks[k]["L"]})) for k in names}
inside = lambda y, k: span[k][0] + 0.5 < y < span[k][1] - 0.5
# cost(i, j): crossings if lane i is left of lane j. i's outgoing lines run over j's lane,
# and j's incoming line runs over i's lane.
cost = {(i, j): sum(inside(y, j) for y in ks[i]["R"]) + inside(ks[j]["L"], i)
for i in names for j in names if i != j}
total = lambda order: sum(cost[(order[a], order[b])] for a in range(len(order)) for b in range(a + 1, len(order)))
if len(names) <= 7:
best, bc = names, total(names)
for perm in itertools.permutations(names):
c = total(perm)
if c < bc:
best, bc = list(perm), c
return best
order, improved = list(names), True # many lanes: adjacent swaps
while improved:
improved = False
for a in range(len(order) - 1):
t = order[:a] + [order[a + 1], order[a]] + order[a + 2:]
if total(t) < total(order):
order, improved = t, True
return order
# --------------------------------------------------------------------------
# main build
# --------------------------------------------------------------------------
def ranges(nums):
nums, out, i = sorted(nums), [], 0
while i < len(nums):
j = i
while j + 1 < len(nums) and nums[j + 1] == nums[j] + 1:
j += 1
out.append(f"CH{nums[i]}" if i == j else f"CH{nums[i]}–{nums[j]}")
i = j + 1
return ", ".join(out)
def attr(s):
return escape(s, {'"': """})
def build(model_path, xlsx_path, orientation, issues):
met = Metrics()
d = load_model(model_path)
if not isinstance(d, dict) or "mixData" not in d:
sys.exit("No 'mixData' found - is this an EdgeTX model YAML file?")
xl = read_workbook(xlsx_path, issues)
M = Model(d, xl, issues)
rows = M.rows()
# ---- nodes and edges -------------------------------------------------
used = set(rows)
edges, seen = [], set()
for ch, rs in rows.items():
for i, r in enumerate(rs):
for a, kind in ((r["src"], "src"), (r["curve"], "curve")):
if a is None or (a, ch, i) in seen:
continue
seen.add((a, ch, i))
if a not in M.lim and a not in xl["name"] and a not in rows:
issues.append(f"CH{a} is used by CH{ch} but has no name or mixer lines")
used.add(a)
edges.append(dict(a=a, b=ch, row=i, kind=kind, back=False))
if not used:
sys.exit("The model has no mixer lines.")
for ch in used:
if ch not in rows:
rows[ch] = [dict(l1="(no mixer lines)", mods=[], src=None, curve=None, empty=True)]
for ch, name in xl["name"].items():
if ch in used and M.lim.get(ch) and M.lim[ch] != name:
issues.append(f"CH{ch}: YAML name '{M.lim[ch]}' differs from workbook name '{name}'")
adj = {}
for e in edges:
adj.setdefault(e["a"], set()).add(e["b"])
back = find_back_edges(used, adj)
for e in edges:
if e["a"] == e["b"] or (e["a"], e["b"]) in back:
e["back"] = True
issues.append(f"CH{e['a']} -> CH{e['b']} closes a cycle (drawn red)")
fwd = {(e["a"], e["b"]) for e in edges if not e["back"]}
lay = assign_layers(used, fwd)
# ---- node geometry (unscaled) ------------------------------------------
labels = {ch: met.fit(short_label(xl["desc"].get(ch, "")), 190, FS_SUB) for ch in used}
W = max(135, min(200, max(met.width(r["l1"]) for rs in rows.values() for r in rs) + PAD_X + 2))
W = int(W)
for ch in used:
labels[ch] = met.fit(short_label(xl["desc"].get(ch, "")), W - 8, FS_SUB)
geo = {}
for ch in used:
hdr = 26 if labels[ch] else 16
rlist, y = [], hdr + 2
for r in rows[ch]:
lines = [r["l1"]] + met.wrap(r["mods"], W - PAD_X)
h = LINE_H * len(lines) + 5
rlist.append(dict(lines=lines, y=y, h=h))
y += h
geo[ch] = dict(hdr=hdr, rows=rlist, h=y + 2)
height = {ch: geo[ch]["h"] for ch in used}
# ---- chains with dummies for long edges --------------------------------
chains, fe = [], [e for e in edges if not e["back"]]
for idx, e in enumerate(fe):
n = lay[e["b"]] - lay[e["a"]]
e["seq"] = [e["a"]] + [("d", idx, k) for k in range(1, n)] + [e["b"]]
e["idx"] = idx
# one chain per distinct (a, b) pair is enough for ordering
pairs = {}
for e in fe:
pairs.setdefault((e["a"], e["b"]), e["seq"])
e["seq"] = pairs[(e["a"], e["b"])] if (e["a"], e["b"]) in pairs else e["seq"]
chains = list(pairs.values())
isolated = [[n] for n in used if all(n not in s for s in chains)]
layers, top, layer_of, H = order_and_place(used, lay, chains + isolated, height)
nlay = len(layers)
# ---- lanes in the gaps between columns ---------------------------------
cy = lambda n: top[n] + H[n] / 2
def rowy(ch, i, f=0.5):
r = geo[ch]["rows"][i]
return top[ch] + r["y"] + (r["h"] - 1) * f
inc = {} # several edges into one row get separate entry points
for e in fe:
inc.setdefault((e["b"], e["row"]), []).append(e)
for es in inc.values():
es.sort(key=lambda e: cy(e["a"]))
for k, e in enumerate(es):
e["fy"] = 0.5 if len(es) == 1 else (k + 1) / (len(es) + 1)
keys = {} # gap -> lane key -> left arm y, right arm ys
for e in fe:
seq = e["seq"]
for i in range(len(seq) - 1):
u, v = seq[i], seq[i + 1]
yto = rowy(e["b"], e["row"], e["fy"]) if i == len(seq) - 2 else cy(v)
key = ("S", e["a"]) if i == 0 else ("E", e["idx"])
d = keys.setdefault(layer_of[u], {}).setdefault(key, dict(L=cy(u), R=set()))
d["R"].add(yto)
maxn = max((len(v) for v in keys.values()), default=1)
GAP = max(40, 2 * LANE_M + LANE_SP * (maxn - 1))
colx = lambda k: k * (W + GAP)
lane = {}
for g, ks in keys.items():
order = lane_order(ks)
x0, span = colx(g) + W + LANE_M, GAP - 2 * LANE_M
for j, k in enumerate(order):
lane[(g, k)] = x0 + (j * span / (len(order) - 1) if len(order) > 1 else span / 2)
content_w = nlay * W + (nlay - 1) * GAP
content_h = max((top[n] + H[n] for n in top), default=1)
# ---- page choice and scale ---------------------------------------------
best = None
for name, (pw, ph) in (("landscape", A4_LAND), ("portrait", A4_LAND[::-1])):
if orientation in ("auto", name):
aw, ah = pw - 2 * MARGIN, ph - TITLE_H - LEGEND_H - MARGIN
s = min(aw / content_w, ah / content_h, 1.0)
if best is None or s > best[0] + 1e-9:
best = (s, name, pw, ph)
s, oname, PW, PH = best
if s < 0.6:
issues.append(f"diagram scaled to {s:.0%} to fit one A4 page - text will be small")
ox = (PW - content_w * s) / 2
oy = TITLE_H + MARGIN / 2 + (PH - TITLE_H - LEGEND_H - MARGIN - content_h * s) / 2
X = lambda x: ox + x * s
Y = lambda y: oy + y * s
# ---- colour groups -----------------------------------------------------
terminal = {n for n in used if not any(e["a"] == n and e["b"] != n for e in edges)}
if xl["group"]:
gname = {ch: xl["group"].get(ch, "Other") for ch in used}
order = [g for g in xl["group_order"] if g in gname.values()]
order += [g for g in ("Other",) if g in gname.values() and g not in order]
else:
gname = {ch: ("Not used by other channels" if ch in terminal else "Feeds other channels")
for ch in used}
order = [g for g in ("Not used by other channels", "Feeds other channels") if g in gname.values()]
style_of = {g: PALETTE[min(i, len(PALETTE) - 1)] for i, g in enumerate(order)}
# ---- emit XML ----------------------------------------------------------
cells, prims = [], []
fnt = lambda v: round(v * s, 1)
for ch in sorted(used):
g = geo[ch]
fill, stroke = style_of[gname[ch]]
x, y, w, h = X(colx(lay[ch])), Y(top[ch]), W * s, g["h"] * s
head = f"{escape(M.chname(ch))}" + (f"
{escape(labels[ch])}" if labels[ch] else "")
cells.append(
f''
f'')
prims.append(("node", x, y, w, h, fill, stroke, M.chname(ch), labels[ch], g["hdr"] * s))
for i, r in enumerate(g["rows"]):
first, rest = r["lines"][0], r["lines"][1:]
empty = rows[ch][i].get("empty")
mcol = MODE_COL.get(rows[ch][i].get("mode"))
html = (f'{escape(first)}' if mcol else escape(first)) + "".join(f'
{escape(t)}' for t in rest)
if empty:
html = f'{escape(first)}'
cells.append(
f''
f'')
prims.append(("row", x + 3 * s, y + r["y"] * s, (W - 6) * s, (r["h"] - 1) * s, r["lines"], mcol or "black"))
base = ("edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;endSize=4;strokeWidth=1;"
"jumpStyle=arc;jumpSize={jump};exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY={ey:.3f};entryDx=0;entryDy=0;")
# Stacking order (= drawing order in draw.io): keep all lines of one channel together. Lines of one
# channel share a lane and lie on top of each other, so if another line crossed them from *between*
# them in the stacking order, it would hop over one and be hopped by the other at the same spot.
fe.sort(key=lambda e: (e["a"], e["b"], e["row"], e["kind"]))
for k, e in enumerate(fe):
seq, pts = e["seq"], []
for i in range(len(seq) - 1):
g_ = layer_of[seq[i]]
xl_ = lane[(g_, ("S", e["a"]) if i == 0 else ("E", e["idx"]))]
yfrom = cy(seq[i])
yto = rowy(e["b"], e["row"], e["fy"]) if i == len(seq) - 2 else cy(seq[i + 1])
pts += [(xl_, yfrom), (xl_, yto)]
pts = [p for j, p in enumerate(pts) if j == 0 or p != pts[j - 1]]
pts = [(X(px), Y(py)) for px, py in pts]
dashed = e["kind"] == "curve"
st = base.format(ey=e["fy"], jump=JUMP) + ("dashed=1;dashPattern=4 2;strokeColor=#1f6fbf;" if dashed else "strokeColor=#444444;")
cells.append(
f''
f''
+ "".join(f'' for px, py in pts)
+ "")
x1 = X(colx(lay[e["a"]]) + W)
x2 = X(colx(lay[e["b"]]) + 3)
prims.append(("edge", [(x1, Y(cy(e["a"])))] + pts + [(x2, Y(rowy(e["b"], e["row"], e["fy"])))], dashed, False, e["a"]))
bus = {} # channel -> its shared lane and targets
for e in fe:
seq = e["seq"]
x = lane[(layer_of[seq[0]], ("S", e["a"]))]
yt = rowy(e["b"], e["row"], e["fy"]) if len(seq) == 2 else cy(seq[1])
b = bus.setdefault(e["a"], dict(x=x, ys=set(), dashed=[]))
b["ys"].add(round(yt, 2))
b["dashed"].append(e["kind"] == "curve")
ndots = 0
for a, b in bus.items():
ya = round(cy(a), 2)
allys = b["ys"] | {ya}
lo, hi = min(allys), max(allys)
for y in sorted(allys):
arms = (y == ya) + (y in b["ys"]) + (y > lo) + (y < hi)
if arms >= 3:
col = "#1f6fbf" if all(b["dashed"]) else "#444444"
cells.append(f'')
prims.append(("dot", X(b["x"]), Y(y), col))
ndots += 1
bk = [e for e in edges if e["back"] and e["a"] != e["b"]]
for k, e in enumerate(bk):
st = ("edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;endSize=4;strokeColor=#cc0000;"
"dashed=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0.5;entryDx=0;entryDy=0;")
cells.append(f'')
prims.append(("edge", [(X(colx(lay[e["a"]])), Y(cy(e["a"]))),
(X(colx(lay[e["b"]]) + W), Y(rowy(e["b"], e["row"])))], True, True, e["a"]))
# ---- title, legend, key ------------------------------------------------
def text(i, x, y, w, h, html, fs=8, extra=""):
cells.append(f''
f'')
mname = (d.get("header") or {}).get("name") or os.path.splitext(os.path.basename(model_path))[0]
ver = f" (EdgeTX {d['semver']})" if d.get("semver") else ""
text("title", MARGIN, 12, PW - 2 * MARGIN, 36,
f'{escape(str(mname))} – channel dependency graph
'
f'Model file{escape(ver)} · arrows run from a channel to the mixer line that '
f'uses it · only channels with mixer lines, or used by another channel, are shown')
prims.append(("text", MARGIN, 12, f"{mname} – channel dependency graph"))
items = []
for g in order:
members = [c for c in used if gname[c] == g]
items.append(("box", style_of[g], f"{g} ({ranges(members)})"))
items += [("line", "#444444", False, "channel used as a mixer source"),
("line", "#1f6fbf", True, "channel used as a curve parameter (diff / expo)")]
items += [("font", "#000000", False, "ADD mixer (default)"),
("font", MODE_COL["REPL"], False, "REPL mixer (replaces lines above)"),
("font", MODE_COL["MUL"], False, "MULT mixer (multiplies)")]
items += [("dot", "#444444", False, "branch: one channel feeding several mixer lines"),
("cross", "#444444", False, "lines crossing without a connection (one hops over the other)")]
if bk:
items.append(("line", "#cc0000", True, "link that closes a cycle"))
ly, lx, lid = PH - LEGEND_H + 6, MARGIN, 0
for it in items:
label = it[-1]
w = met.width(label) + (12 if it[0] == "font" else 40)
if lx + w > PW - MARGIN:
lx, ly = MARGIN, ly + 14
if it[0] == "font":
pass
elif it[0] == "dot":
cells.append(f'')
prims.append(("dot", lx + 13.5, ly + 6, it[1]))
elif it[0] == "cross":
ed = (f'style="endArrow=none;html=1;strokeColor=#444444;jumpStyle=arc;jumpSize={JUMP};" edge="1" parent="1">')
cells.append(f''
f'')
cells.append(f''
f'')
prims.append(("edge", [(lx + 14, ly - 1), (lx + 14, ly + 13)], False, False, "L1"))
prims.append(("edge", [(lx, ly + 6), (lx + 28, ly + 6)], False, False, "L2"))
elif it[0] == "box":
cells.append(f'')
prims.append(("box", lx, ly + 1, it[1]))
else:
cells.append(f''
f''
f'')
prims.append(("edge", [(lx, ly + 6), (lx + 28, ly + 6)], it[2], it[1] == "#cc0000", "L0"))
tx = lx if it[0] == "font" else lx + 34
lab_html = f'{escape(label)}' if it[0] == "font" else escape(label)
text(f"lgt{lid}", tx, ly - 1, w, 12, lab_html)
prims.append(("label", tx, ly - 1, label, it[1] if it[0] == "font" else "black"))
lx += w + 14
lid += 1
key = ("Mixer line = source weight / modifiers. Font colour shows the mixer type: black = add, orange = REPL (replace), purple = MULT (multiply). "
"otherwise add (colours as in the legend). I = input, Trm = trim, GV = global variable, CV = curve, L = logical switch, FM = flight mode(s) "
"in which the line is active, off = offset. Bold outline = channel not used by any other channel. "
"A dot marks a branch; lines that cross without a dot are not connected.")
text("key", MARGIN, ly + 16, PW - 2 * MARGIN, 24, key, 7.5, "fontColor=#555555;")
xml = (''
f''
'' + "".join(cells) + "")
ncross, ncramped = check_routes(prims, issues)
info = dict(nodes=len(used), edges=len(edges), layers=nlay, page=oname, scale=s,
crossings=ncross, branches=ndots, cramped=ncramped)
return xml, prims, (PW, PH), info, met
# --------------------------------------------------------------------------
# optional PNG preview (approximate rendering, for a quick look)
# --------------------------------------------------------------------------
def _route_edges(prims):
"""(index, polyline) of every orthogonally routed edge (legend samples and red cycle links excluded)."""
return [(i, p[1], p[4]) for i, p in enumerate(prims)
if p[0] == "edge" and not str(p[4]).startswith("L") and not p[3]]
def find_crossings(prims):
"""Every place where two routed edges cross, as drawn by draw.io (the later edge hops over the earlier).
-> [(later edge index, x, y, hop is on a horizontal line?, clearance)] where clearance is the distance
from the crossing to the nearest bend or end of the two lines."""
es, out, seen = _route_edges(prims), [], set()
for a in range(len(es)):
for b in range(a + 1, len(es)):
for (x1, y1), (x2, y2) in zip(es[a][1], es[a][1][1:]):
for (x3, y3), (x4, y4) in zip(es[b][1], es[b][1][1:]):
ah, bh = abs(y1 - y2) < 1e-6, abs(y3 - y4) < 1e-6
if ah == bh: # parallel: not a crossing
continue
(hx1, hx2, hy), (vy1, vy2, vx) = ((x1, x2, y1), (y3, y4, x3)) if ah else ((x3, x4, y3), (y1, y2, x1))
if min(hx1, hx2) + 0.5 < vx < max(hx1, hx2) - 0.5 and min(vy1, vy2) + 0.5 < hy < max(vy1, vy2) - 0.5:
clear = min(abs(vx - hx1), abs(vx - hx2), abs(hy - vy1), abs(hy - vy2))
k = (round(vx, 1), round(hy, 1)) # lines of one channel can lie on top of
if k not in seen: # each other: one visible crossing
seen.add(k)
out.append((es[b][0], vx, hy, not ah, clear))
return out
def check_routes(prims, issues):
"""Self-check of the routing. Adds a warning for anything that could mislead the reader."""
cr = find_crossings(prims)
near = [c for c in cr if c[4] < NEAR]
if near:
issues.append(f"{len(near)} line crossing(s) are closer than {NEAR:.0f} px to a bend or box edge "
"- the line-jump arc may look cramped")
es = _route_edges(prims)
for a in range(len(es)): # different lines running along each other
for b in range(a + 1, len(es)):
if es[a][2] == es[b][2]: # lines of one channel share a lane on purpose
continue
for (x1, y1), (x2, y2) in zip(es[a][1], es[a][1][1:]):
for (x3, y3), (x4, y4) in zip(es[b][1], es[b][1][1:]):
same_h = abs(y1 - y2) < 1e-6 and abs(y3 - y4) < 1e-6 and abs(y1 - y3) < 1.0
same_v = abs(x1 - x2) < 1e-6 and abs(x3 - x4) < 1e-6 and abs(x1 - x3) < 1.0
if same_h and min(max(x1, x2), max(x3, x4)) - max(min(x1, x2), min(x3, x4)) > 3:
issues.append("two lines run on top of each other (could be read as one line)")
if same_v and min(max(y1, y2), max(y3, y4)) - max(min(y1, y2), min(y3, y4)) > 3:
issues.append("two lines run on top of each other (could be read as one line)")
# Stacking order at every crossing: draw.io makes the later line hop over the earlier one. That is only
# unambiguous if every horizontal line through the point is stacked entirely above, or entirely below,
# every vertical line through it. Otherwise two different hops are drawn at the same place.
for px, py in {(round(c[1], 1), round(c[2], 1)) for c in cr}:
hz, vt = [], []
for n, (_, poly, _) in enumerate(es):
for (x1, y1), (x2, y2) in zip(poly, poly[1:]):
if abs(y1 - y2) < 1e-6 and abs(y1 - py) < 0.6 and min(x1, x2) - 0.6 <= px <= max(x1, x2) + 0.6:
hz.append(n)
if abs(x1 - x2) < 1e-6 and abs(x1 - px) < 0.6 and min(y1, y2) - 0.6 <= py <= max(y1, y2) + 0.6:
vt.append(n)
if hz and vt and not (max(hz) < min(vt) or max(vt) < min(hz)):
issues.append(f"stacking-order conflict at a crossing near ({px:.0f}, {py:.0f}): two hops overlap")
boxes = [p for p in prims if p[0] == "node"]
for i, pts, _ in es: # a line running through a box
for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
for b in boxes:
bx, by, bw, bh = b[1] + 4, b[2] + 1.5, b[3] - 8, b[4] - 3 # rows are inset 3 px
if min(x1, x2) < bx + bw and max(x1, x2) > bx and min(y1, y2) < by + bh and max(y1, y2) > by:
issues.append(f"a line passes through the box {b[7]}")
return len(cr), len(near)
def hopped_paths(prims):
"""For the PNG preview: each routed edge's polyline with a small semicircular hop added wherever it
crosses an edge that is drawn before it (what draw.io's jumpStyle=arc does). The hop is part of the
hopping line itself, so nothing is erased and the line it hops over stays unbroken."""
es, out = _route_edges(prims), {}
for b, (ib, ptsb, _) in enumerate(es):
path = [ptsb[0]]
for (x3, y3), (x4, y4) in zip(ptsb, ptsb[1:]):
horiz = abs(y3 - y4) < 1e-6
hits = []
for a in range(b):
for (x1, y1), (x2, y2) in zip(es[a][1], es[a][1][1:]):
if horiz == (abs(y1 - y2) < 1e-6): # parallel
continue
vx, hy = (x1, y3) if horiz else (x3, y1)
hx0, hx1 = sorted((x3, x4)) if horiz else sorted((x1, x2))
vy0, vy1 = sorted((y1, y2)) if horiz else sorted((y3, y4))
if hx0 + 0.5 < vx < hx1 - 0.5 and vy0 + 0.5 < hy < vy1 - 0.5:
hits.append((vx, hy))
d = (1 if x4 > x3 else -1) if horiz else (1 if y4 > y3 else -1)
along = (lambda h: h[0] * d) if horiz else (lambda h: h[1] * d)
hits.sort(key=along)
a0, a1, last = (x3 * d, x4 * d, -1e9) if horiz else (y3 * d, y4 * d, -1e9)
for hx, hy in hits:
pos = along((hx, hy))
r = min(JUMP, pos - a0, a1 - pos) # the arc must fit inside this segment
if r < 2 or pos - r < last + 0.1: # no room, or on top of the previous arc
continue
last = pos + r
for k in range(0, 17):
t = math.pi * k / 16
path.append((hx - d * r * math.cos(t), hy - r * math.sin(t)) if horiz
else (hx + r * math.sin(t), hy - d * r * math.cos(t)))
path.append((x4, y4))
out[ib] = path
return out
def preview(path, prims, size, met):
if ImageFont is None:
print("Pillow is not installed - preview skipped", file=sys.stderr)
return
S = 2
im = Image.new("RGB", (size[0] * S, size[1] * S), "white")
dr = ImageDraw.Draw(im)
font = met.font.get(False)
f = lambda sz: font.font_variant(size=int(sz * S)) if font else None
hops = hopped_paths(prims)
for pi, p in enumerate(prims):
if p[0] == "node":
_, x, y, w, h, fill, stroke, name, lab, hdr = p
dr.rectangle([x * S, y * S, (x + w) * S, (y + h) * S], fill=fill, outline=stroke, width=2)
dr.text(((x + 4) * S, (y + 2) * S), name, fill="black", font=f(9))
dr.text(((x + 4) * S, (y + 13) * S), lab, fill="black", font=f(8))
elif p[0] == "row":
_, x, y, w, h, lines, mc = p
dr.rectangle([x * S, y * S, (x + w) * S, (y + h) * S], fill="white", outline="#b0b0b0")
for i, t in enumerate(lines):
dr.text(((x + 3) * S, (y + 1 + 10 * i) * S), t, fill=mc if i == 0 else "#666666", font=f(8))
elif p[0] == "edge":
col = "#cc0000" if p[3] else ("#1f6fbf" if p[2] else "#444444")
dr.line([(a * S, b * S) for a, b in hops.get(pi, p[1])], fill=col, width=2, joint="curve")
elif p[0] == "dot":
dr.ellipse([(p[1] - 2.5) * S, (p[2] - 2.5) * S, (p[1] + 2.5) * S, (p[2] + 2.5) * S], fill=p[3])
elif p[0] == "box":
dr.rectangle([p[1] * S, p[2] * S, (p[1] + 14) * S, (p[2] + 10) * S], fill=p[3][0], outline=p[3][1])
elif p[0] in ("label", "text"):
dr.text((p[1] * S, p[2] * S), p[3], fill=p[4] if len(p) > 4 else "black",
font=f(8 if p[0] == "label" else 14))
dr.rectangle([0, 0, size[0] * S - 1, size[1] * S - 1], outline="#999999") # A4 page edge
im.save(path)
def main():
ap = argparse.ArgumentParser(description="EdgeTX channel dependency diagram (draw.io)")
ap.add_argument("model", help="EdgeTX model YAML file")
ap.add_argument("reference", nargs="?", help="optional Excel reference workbook (labels only)")
ap.add_argument("-o", "--output", help="output .drawio file (default: next to the YAML)")
ap.add_argument("--orientation", choices=("auto", "landscape", "portrait"), default="auto")
ap.add_argument("--preview", metavar="PNG", help="also write an approximate PNG preview (needs Pillow)")
ap.add_argument("--list-issues", action="store_true", help="print every warning in full")
a = ap.parse_args()
issues = []
try:
xml, prims, size, info, met = build(a.model, a.reference, a.orientation, issues)
except FileNotFoundError as err:
sys.exit(f"File not found: {err.filename}")
except yaml.YAMLError as err:
sys.exit(f"{a.model} could not be read as YAML ({err}). Is it an EdgeTX model file?")
except UnicodeDecodeError:
sys.exit(f"{a.model} is not a text file. The first argument must be the EdgeTX .yml model.")
except Exception as err: # e.g. a workbook that cannot be opened
sys.exit(f"Failed: {type(err).__name__}: {err}")
out = a.output or os.path.splitext(a.model)[0] + "_channels.drawio"
with open(out, "w", encoding="utf-8") as fh:
fh.write(xml)
print(f"{out}: {info['nodes']} channels, {info['edges']} dependencies, {info['layers']} columns, "
f"A4 {info['page']}, scale {info['scale']:.0%}, {info['branches']} branch dots, "
f"{info['crossings']} crossings")
if a.preview:
preview(a.preview, prims, size, met)
uniq = list(dict.fromkeys(issues))
if uniq:
if a.list_issues:
print(f"{len(uniq)} warning(s):")
for i in uniq:
print(" -", i)
else:
print(f"{len(uniq)} warning(s) - run again with --list-issues to see them")
if __name__ == "__main__":
main()