Repository navigation
Expand file tree
/
Copy pathnode.py
More file actions
executable file
·157 lines (134 loc) · 4.65 KB
/
Copy pathnode.py
File metadata and controls
executable file
·157 lines (134 loc) · 4.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python3
"""
node.py — UAVCAN-style CAN messenger. Same code on EULER and NEWTON.
Usage:
python3 node.py euler # allowed priorities: 0, 3
python3 node.py newton # allowed priorities: 1, 2
Input format (typed into stdin):
##P TEXT # P = priority digit, TEXT alphanumeric, <= 6 chars
Examples:
##0 HI
##3 BYE
##1 HELLO
The CAN arbitration ID is set equal to the priority digit P, matching the
UAVCAN convention (lower ID = higher priority).
"""
import re
import sys
import threading
from datetime import datetime
import can
# ---------------------------------------------------------------------- ANSI
class C:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREY = "\033[38;5;245m"
WHITE = "\033[97m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
ORANGE = "\033[38;5;208m"
LIME = "\033[38;5;154m"
# Per-priority accent color (used to tint the priority tag itself).
PRIO_COLOR = {
0: C.RED, # P0 = highest priority -> red
1: C.ORANGE,
2: C.YELLOW,
3: C.LIME,
}
# Per-role banner color.
ROLES = {
"euler": {"send": (0, 3), "name": "EULER", "color": C.MAGENTA},
"newton": {"send": (1, 2), "name": "NEWTON", "color": C.BLUE},
}
# Input line format: ##P TEXT
INPUT_RE = re.compile(r"^##([0-3])\s+([A-Za-z0-9]{1,6})\s*$")
def now() -> str:
return datetime.now().strftime("%H:%M:%S")
def fmt_prio(prio: int) -> str:
return f"{PRIO_COLOR.get(prio, C.WHITE)}{C.BOLD}P{prio}{C.RESET}"
def rx_loop(bus: can.BusABC) -> None:
"""Print every received frame on its own line, in color."""
while True:
msg = bus.recv()
if msg is None:
continue
try:
text = bytes(msg.data).decode("ascii", errors="replace").rstrip("\x00")
except Exception:
text = msg.data.hex()
prio = msg.arbitration_id
print(
f"{C.GREY}[{now()}]{C.RESET} "
f"{C.GREEN}{C.BOLD}RX{C.RESET} {fmt_prio(prio)} "
f"{C.CYAN}{C.BOLD}{text}{C.RESET}",
flush=True,
)
def main() -> None:
if len(sys.argv) != 2 or sys.argv[1] not in ROLES:
print("usage: node.py {euler|newton}", file=sys.stderr)
sys.exit(2)
role = sys.argv[1]
cfg = ROLES[role]
bus = can.Bus(interface="socketcan", channel="can0")
banner = cfg["color"]
name = cfg["name"]
print(
f"{banner}{C.BOLD}╔══════════════════════════════════════════════╗{C.RESET}\n"
f"{banner}{C.BOLD}║ {name:<6} up on can0 • may send {cfg['send']} ║{C.RESET}\n"
f"{banner}{C.BOLD}╚══════════════════════════════════════════════╝{C.RESET}",
flush=True,
)
allowed = ", ".join(f"{PRIO_COLOR[p]}{C.BOLD}P{p}{C.RESET}" for p in cfg["send"])
print(
f"{C.DIM}type:{C.RESET} {C.WHITE}{C.BOLD}##P TEXT{C.RESET} "
f"{C.DIM}(P in {{{C.RESET}{allowed}{C.DIM}}}, TEXT alnum ≤6){C.RESET}",
flush=True,
)
threading.Thread(target=rx_loop, args=(bus,), daemon=True).start()
for line in sys.stdin:
line = line.strip()
if not line:
continue
m = INPUT_RE.match(line)
if not m:
print(
f"{C.RED}{C.BOLD}!!{C.RESET} {C.RED}bad format:{C.RESET} {line!r} "
f"{C.DIM}(expected ##P TEXT){C.RESET}",
flush=True,
)
continue
prio = int(m.group(1))
text = m.group(2)
if prio not in cfg["send"]:
print(
f"{C.RED}{C.BOLD}!!{C.RESET} priority {fmt_prio(prio)} "
f"{C.RED}not allowed on {name}{C.RESET} "
f"{C.DIM}(allowed: {cfg['send']}){C.RESET}",
flush=True,
)
continue
frame = can.Message(
arbitration_id=prio,
is_extended_id=False,
data=text.encode("ascii")[:8],
)
try:
bus.send(frame)
# Sender shows NO timestamp (per spec).
print(
f"{C.YELLOW}{C.BOLD}TX{C.RESET} {fmt_prio(prio)} "
f"{C.WHITE}{text}{C.RESET}",
flush=True,
)
except can.CanError as e:
print(f"{C.RED}{C.BOLD}!! send failed:{C.RESET} {e}", flush=True)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass