-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathtimecard-config.py
More file actions
481 lines (419 loc) · 19.2 KB
/
Copy pathtimecard-config.py
File metadata and controls
481 lines (419 loc) · 19.2 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env python3
import os
os.environ.setdefault('ESCDELAY', '25')
import curses
import time
import argparse
import random
from collections import deque
class DataHistory:
def __init__(self, max_len=50):
self.max_len = max_len
self.data = deque(maxlen=max_len)
def add(self, value):
try:
val = float(value)
self.data.append(val)
except (ValueError, TypeError):
pass
def get_stats(self):
if not self.data:
return 0, 0, 0
return min(self.data), max(self.data), self.data[-1]
class TimeCardManager:
BASE_PATH = "/sys/class/timecard"
def __init__(self, demo_mode=False):
self.demo_mode = demo_mode
self.cards = []
self.mock_data = {}
if self.demo_mode:
self._init_mock_data()
else:
self.refresh_cards()
def _init_mock_data(self):
self.cards = ["ocp0", "ocp1"]
for card in self.cards:
self.mock_data[card] = {
"serialnum": f"TC-{random.randint(1000, 9999)}",
"gnss_sync": "1",
"clock_source": "GNSS",
"available_clock_sources": "GNSS ATOMIC PTP EXTERNAL",
"clock_status_drift": "0.123",
"clock_status_offset": "0.005",
"sma1": "PPS_OUT",
"sma2": "10MHz_OUT",
"sma3": "PPS_IN",
"sma4": "NONE",
"available_sma_inputs": "PPS_IN 10MHz_IN NONE",
"available_sma_outputs": "PPS_OUT 10MHz_OUT NONE",
"utc_tai_offset": "37",
"external_pps_cable_delay": "100",
"internal_pps_cable_delay": "50",
"irig_b_mode": "B002",
"tod_protocol": "NMEA",
"available_tod_protocols": "NMEA UBX TSIP",
"tod_baud_rate": "115200",
"available_tod_baud_rates": "9600 19200 38400 57600 115200",
"tod_correction": "0"
}
def refresh_cards(self):
if self.demo_mode:
return
if not os.path.exists(self.BASE_PATH):
self.cards = []
return
self.cards = sorted([d for d in os.listdir(self.BASE_PATH) if d.startswith("ocp")])
def get_attr(self, card, attr):
if self.demo_mode:
# Simulate slight drift/offset changes
if attr == "clock_status_drift":
val = float(self.mock_data[card][attr]) + (random.random() - 0.5) * 0.01
self.mock_data[card][attr] = f"{val:.4f}"
elif attr == "clock_status_offset":
val = float(self.mock_data[card][attr]) + (random.random() - 0.5) * 0.001
self.mock_data[card][attr] = f"{val:.4f}"
return self.mock_data[card].get(attr, "N/A")
path = os.path.join(self.BASE_PATH, card, attr)
try:
with open(path, "r") as f:
return f.read().strip()
except Exception:
return "N/A"
def set_attr(self, card, attr, value):
if self.demo_mode:
self.mock_data[card][attr] = str(value)
return True
path = os.path.join(self.BASE_PATH, card, attr)
try:
with open(path, "w") as f:
f.write(str(value))
return True
except Exception as e:
return False
class TimeCardUI:
def __init__(self, stdscr, manager):
self.stdscr = stdscr
self.manager = manager
self.current_card_idx = 0
self.running = True
self.menu_idx = 0
self.sub_menu_idx = 0
self.mode = "DASHBOARD" # DASHBOARD, CONFIG_SMA, CONFIG_TIMING, CONFIG_TOD
self.history = {
"drift": {}, # card_name -> DataHistory
"offset": {} # card_name -> DataHistory
}
# UI colors
curses.start_color()
curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # Header
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) # Values
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Selection
curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK) # Errors
curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLUE) # Highlight
def draw_header(self):
h, w = self.stdscr.getmaxyx()
title = " TimeCard Configurator "
self.stdscr.attron(curses.color_pair(5) | curses.A_BOLD)
self.stdscr.addstr(0, (w - len(title)) // 2, title)
self.stdscr.attroff(curses.color_pair(5) | curses.A_BOLD)
status_line = f" Card: {self.get_current_card()} | Mode: {self.mode} | Press 'q' to quit, 'TAB' to switch card "
self.stdscr.addstr(1, 0, status_line[:w-1])
self.stdscr.addstr(2, 0, "=" * w)
def get_current_card(self):
if not self.manager.cards:
return "No Cards Found"
return self.manager.cards[self.current_card_idx]
def draw_dashboard(self):
self.stdscr.attron(curses.A_BOLD)
self.stdscr.addstr(4, 2, "--- Dashboard ---")
self.stdscr.attroff(curses.A_BOLD)
card = self.get_current_card()
if card == "No Cards Found":
self.stdscr.addstr(6, 5, "No TimeCard devices found in /sys/class/timecard/", curses.color_pair(4))
return
# Initialize history for this card if not exists
if card not in self.history["drift"]:
self.history["drift"][card] = DataHistory()
self.history["offset"][card] = DataHistory()
attrs = [
("Serial Number", "serialnum"),
("GNSS Sync Status", "gnss_sync"),
("Clock Source", "clock_source"),
("Clock Drift", "clock_status_drift"),
("Clock Offset", "clock_status_offset"),
("UTC/TAI Offset", "utc_tai_offset")
]
for i, (label, attr) in enumerate(attrs):
val = self.manager.get_attr(card, attr)
if attr == "clock_status_drift":
self.history["drift"][card].add(val)
elif attr == "clock_status_offset":
self.history["offset"][card].add(val)
self.stdscr.addstr(6 + i, 4, f"{label:20}: ")
self.stdscr.addstr(val, curses.color_pair(2) | curses.A_BOLD)
# Draw Graphs
h, w = self.stdscr.getmaxyx()
graph_w = min(w // 2 - 10, 50)
graph_h = 5
self.draw_graph(6, w // 2, graph_h, graph_w, self.history["drift"][card], "Drift History")
self.draw_graph(14, w // 2, graph_h, graph_w, self.history["offset"][card], "Offset History")
self.stdscr.addstr(14, 2, "Menu (Use Arrow Keys & Enter):")
menu_items = ["SMA Configuration", "Timing Configuration", "ToD Configuration", "About"]
for i, item in enumerate(menu_items):
style = curses.A_REVERSE if (self.menu_idx == i and self.mode == "DASHBOARD") else curses.A_NORMAL
self.stdscr.addstr(16 + i, 4, f"{i+1}. {item}", style)
def draw_about(self):
self.stdscr.attron(curses.A_BOLD)
self.stdscr.addstr(4, 2, "--- About ---")
self.stdscr.attroff(curses.A_BOLD)
info = [
"Time Card Configurator v1.0",
"",
"A comprehensive ncurses tool for configuring and monitoring",
"the Time Card driver via sysfs.",
"",
"Project: Time Card (https://github.com/opencomputeproject/Time-Card)",
"Maintainer: Ahmad Byagowi",
"",
"Features:",
"- Real-time GNSS sync and clock monitoring",
"- Interactive SMA mapping and timing configuration",
"- Support for multiple Time Card instances",
"- Visual representation of clock drift and offset",
"",
"Press 'Backspace' to return to Dashboard."
]
for i, line in enumerate(info):
self.stdscr.addstr(6 + i, 4, line)
def draw_graph(self, y, x, height, width, history, title):
self.stdscr.addstr(y, x, f" {title} ", curses.A_BOLD | curses.color_pair(1))
if not history.data:
self.stdscr.addstr(y + 2, x + 2, "Waiting for data...", curses.A_DIM)
return
min_v, max_v, last_v = history.get_stats()
v_range = max_v - min_v
if v_range == 0: v_range = 1.0
# Draw axes/box
for i in range(height):
self.stdscr.addch(y + 1 + i, x, curses.ACS_VLINE)
self.stdscr.addch(y + height + 1, x, curses.ACS_LLCORNER)
self.stdscr.hline(y + height + 1, x + 1, curses.ACS_HLINE, width)
# Plot data
data_points = list(history.data)
for i, val in enumerate(data_points[-width:]):
norm_v = (val - min_v) / v_range
bar_h = int(norm_v * (height - 1))
self.stdscr.addch(y + height - bar_h, x + 1 + i, "o", curses.color_pair(2))
self.stdscr.addstr(y + height + 2, x, f"L:{last_v:.4f} Min:{min_v:.4f} Max:{max_v:.4f}")
def draw_sma_config(self):
card = self.get_current_card()
self.stdscr.attron(curses.A_BOLD)
self.stdscr.addstr(4, 2, f"--- SMA Configuration for {card} ---")
self.stdscr.attroff(curses.A_BOLD)
# Dynamic ASCII Art for SMA
sma_vals = [self.manager.get_attr(card, f"sma{i}") for i in range(1, 5)]
sma_modes = []
for v in sma_vals:
if "IN" in v: sma_modes.append("I")
elif "OUT" in v: sma_modes.append("O")
else: sma_modes.append("-")
sma_art = [
" _---_ ",
" / SMA \\ ",
f" |{' '.join([str(i) for i in range(1, 5)]):^7}| ",
f" |{' '.join(sma_modes):^7}| ",
" \\_____/ ",
" | | "
]
h, w = self.stdscr.getmaxyx()
for i, line in enumerate(sma_art):
self.stdscr.addstr(6 + i, w - 25, line, curses.color_pair(1))
smas = [("SMA1", "sma1"), ("SMA2", "sma2"), ("SMA3", "sma3"), ("SMA4", "sma4")]
for i, (label, attr) in enumerate(smas):
val = self.manager.get_attr(card, attr)
style = curses.A_REVERSE if self.sub_menu_idx == i else curses.A_NORMAL
self.stdscr.addstr(6 + i, 4, f"{label:5}: {val}", style)
self.stdscr.addstr(12, 2, "Selection Menu:")
self.stdscr.addstr(13, 4, "- Arrow UP/DOWN to select SMA")
self.stdscr.addstr(14, 4, "- 'Enter' to cycle values")
self.stdscr.addstr(15, 4, "- 'Backspace' to return")
def draw_timing_config(self):
card = self.get_current_card()
self.stdscr.attron(curses.A_BOLD)
self.stdscr.addstr(4, 2, f"--- Timing Configuration for {card} ---")
self.stdscr.attroff(curses.A_BOLD)
# Dynamic ASCII Art for Timing
sync = self.manager.get_attr(card, "gnss_sync")
is_locked = sync == "1"
status_text = "LOCKED" if is_locked else "SYNCING"
color = curses.color_pair(2) if is_locked else curses.color_pair(3)
timing_art = [
" _---_ ",
" / \\ ",
f" | {status_text:^7} | ",
" | -O- | ",
" | | | ",
" \\_____/ "
]
h, w = self.stdscr.getmaxyx()
for i, line in enumerate(timing_art):
self.stdscr.addstr(6 + i, w - 25, line, color)
attrs = [
("External PPS Delay", "external_pps_cable_delay"),
("Internal PPS Delay", "internal_pps_cable_delay"),
("UTC/TAI Offset", "utc_tai_offset"),
("IRIG-B Mode", "irig_b_mode")
]
for i, (label, attr) in enumerate(attrs):
val = self.manager.get_attr(card, attr)
style = curses.A_REVERSE if self.sub_menu_idx == i else curses.A_NORMAL
self.stdscr.addstr(6 + i, 4, f"{label:20}: {val}", style)
self.stdscr.addstr(12, 2, "Selection Menu:")
self.stdscr.addstr(13, 4, "- 'Enter' to edit value")
self.stdscr.addstr(14, 4, "- 'Backspace' to return")
def draw_tod_config(self):
card = self.get_current_card()
self.stdscr.attron(curses.A_BOLD)
self.stdscr.addstr(4, 2, f"--- ToD Configuration for {card} ---")
self.stdscr.attroff(curses.A_BOLD)
# Dynamic ASCII Art for ToD
protocol = self.manager.get_attr(card, "tod_protocol")
if protocol == "NMEA":
line2 = "| $GP-NMEA |"
elif protocol == "UBX":
line2 = "| U-BLOX.. |"
else:
line2 = f"| {protocol:^8} |"
tod_art = [
" __________ ",
line2,
" |__________| ",
" | | ",
" __| |__ ",
" |________| "
]
h, w = self.stdscr.getmaxyx()
for i, line in enumerate(tod_art):
self.stdscr.addstr(6 + i, w - 25, line, curses.color_pair(1))
attrs = [
("ToD Protocol", "tod_protocol"),
("ToD Baud Rate", "tod_baud_rate"),
("ToD Correction", "tod_correction")
]
for i, (label, attr) in enumerate(attrs):
val = self.manager.get_attr(card, attr)
style = curses.A_REVERSE if self.sub_menu_idx == i else curses.A_NORMAL
self.stdscr.addstr(6 + i, 4, f"{label:20}: {val}", style)
self.stdscr.addstr(12, 2, "Selection Menu:")
self.stdscr.addstr(13, 4, "- 'Enter' to cycle/edit values")
self.stdscr.addstr(14, 4, "- 'Backspace' to return")
def edit_value(self, card, attr, label):
curses.echo()
curses.curs_set(1)
self.stdscr.addstr(18, 2, f"Enter new value for {label}: ")
self.stdscr.refresh()
new_val = self.stdscr.getstr(18, 30 + len(label)).decode('utf-8')
curses.noecho()
curses.curs_set(0)
if new_val:
self.manager.set_attr(card, attr, new_val)
def cycle_attr(self, card, attr, available_attr):
current = self.manager.get_attr(card, attr)
available = self.manager.get_attr(card, available_attr).split()
if current in available:
idx = (available.index(current) + 1) % len(available)
self.manager.set_attr(card, attr, available[idx])
elif available:
self.manager.set_attr(card, attr, available[0])
def run(self):
self.stdscr.nodelay(True)
curses.curs_set(0)
while self.running:
self.stdscr.erase()
self.draw_header()
if self.mode == "DASHBOARD":
self.draw_dashboard()
elif self.mode == "CONFIG_SMA":
self.draw_sma_config()
elif self.mode == "CONFIG_TIMING":
self.draw_timing_config()
elif self.mode == "CONFIG_TOD":
self.draw_tod_config()
elif self.mode == "ABOUT":
self.draw_about()
self.stdscr.refresh()
try:
ch = self.stdscr.getch()
if ch == ord('q'):
self.running = False
elif ch == ord('\t'):
if self.manager.cards:
self.current_card_idx = (self.current_card_idx + 1) % len(self.manager.cards)
elif ch == curses.KEY_DOWN:
if self.mode == "DASHBOARD":
self.menu_idx = (self.menu_idx + 1) % 4
else:
limit = 4 if self.mode == "CONFIG_SMA" else (4 if self.mode == "CONFIG_TIMING" else 3)
self.sub_menu_idx = (self.sub_menu_idx + 1) % limit
elif ch == curses.KEY_UP:
if self.mode == "DASHBOARD":
self.menu_idx = (self.menu_idx - 1) % 4
else:
limit = 4 if self.mode == "CONFIG_SMA" else (4 if self.mode == "CONFIG_TIMING" else 3)
self.sub_menu_idx = (self.sub_menu_idx - 1) % limit
elif ch == 10: # Enter
card = self.get_current_card()
if card == "No Cards Found":
continue
if self.mode == "DASHBOARD":
if self.menu_idx == 0: self.mode = "CONFIG_SMA"; self.sub_menu_idx = 0
elif self.menu_idx == 1: self.mode = "CONFIG_TIMING"; self.sub_menu_idx = 0
elif self.menu_idx == 2: self.mode = "CONFIG_TOD"; self.sub_menu_idx = 0
elif self.menu_idx == 3: self.mode = "ABOUT"
elif self.mode == "CONFIG_SMA":
smas = ["sma1", "sma2", "sma3", "sma4"]
attr = smas[self.sub_menu_idx]
available = self.manager.get_attr(card, "available_sma_inputs").split() + \
self.manager.get_attr(card, "available_sma_outputs").split()
current = self.manager.get_attr(card, attr)
if current in available:
idx = (available.index(current) + 1) % len(available)
self.manager.set_attr(card, attr, available[idx])
elif available:
self.manager.set_attr(card, attr, available[0])
elif self.mode == "CONFIG_TIMING":
attrs = [
("external_pps_cable_delay", "External PPS Delay"),
("internal_pps_cable_delay", "Internal PPS Delay"),
("utc_tai_offset", "UTC/TAI Offset"),
("irig_b_mode", "IRIG-B Mode")
]
attr, label = attrs[self.sub_menu_idx]
self.edit_value(card, attr, label)
elif self.mode == "CONFIG_TOD":
attrs = [
("tod_protocol", "ToD Protocol"),
("tod_baud_rate", "ToD Baud Rate"),
("tod_correction", "ToD Correction")
]
if self.sub_menu_idx == 0:
self.cycle_attr(card, "tod_protocol", "available_tod_protocols")
elif self.sub_menu_idx == 1:
self.cycle_attr(card, "tod_baud_rate", "available_tod_baud_rates")
elif self.sub_menu_idx == 2:
attr, label = attrs[self.sub_menu_idx]
self.edit_value(card, attr, label)
elif ch == curses.KEY_BACKSPACE or ch == 127 or ch == 27: # Backspace or ESC
self.mode = "DASHBOARD"
time.sleep(0.05)
except KeyboardInterrupt:
break
def main(stdscr, demo_mode):
manager = TimeCardManager(demo_mode=demo_mode)
ui = TimeCardUI(stdscr, manager)
ui.run()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="TimeCard Ncurses Configurator")
parser.add_argument("--demo", action="store_true", help="Run in demo mode with mock data")
args = parser.parse_args()
curses.wrapper(main, args.demo)