-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
executable file
·163 lines (132 loc) · 4.8 KB
/
main.py
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
#!/usr/bin/env python3
"""
Websocket that forwards relevant Network Tables data to the webpage and also caches data for that instance of the page for later use.
"""
import argparse
import datetime
import json
import logging
import os
import signal
import sys
from threading import Thread
from networktables import NetworkTables
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
__author__ = "SumiGovindaraju"
__copyright__ = "Copyright (c) 2018-2019 Sumi Govindaraju"
__credits__ = ["SumiGovindaraju"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "SumiGovindarajut"
parser = argparse.ArgumentParser(
description="FRC-Grapher, " + __copyright__)
parser.add_argument("-c", "--config", help="Path to saved configuration file", metavar="")
parser.add_argument("-i", "--ip", default="localhost",
help="IP address of NetworkTables server", metavar="", type=str)
parser.add_argument("-r", "--replay-match", default=False,
help="path to JSON cache file for match replay", metavar="", type=str)
args = parser.parse_args()
def loadConfig():
ret_val = set()
if args.config:
try:
with open(args.config, 'r') as infile:
data = json.loads(infile.read())
for i in data:
ret_val.add(i)
except FileNotFoundError:
print("Configuration file not found. Using empty set instead.")
else:
print("Configuration file not specified. Using empty set instead.")
return ret_val
keys = loadConfig()
connections = set()
class GrapherWebSocket(WebSocket):
def handleMessage(self):
if (self.data.startswith("Add Dataset: ")):
keys.add(self.data[13:])
elif (self.data == "Save Config"):
filename = "config.json"
if args.config != None:
filename = args.config
with open(filename, 'w') as outfile:
outfile.write(json.dumps(list(keys)))
def handleConnected(self):
connections.add(self)
if args.replay_match:
try:
with open(args.replay_match, 'r') as infile:
for connection in connections:
connection.sendMessage("Replay")
connection.sendMessage(infile.read())
except FileNotFoundError:
print("JSON cache file not found. Exiting...")
sys.exit()
def handleClose(self):
connections.remove(self)
server = SimpleWebSocketServer('localhost', 8254, GrapherWebSocket)
global currentTimestamp
currentTimestamp = 0
datasets = {}
colors = [
'rgb(255, 99, 132)',
'rgb(201, 203, 207)',
'rgb(255, 159, 64)',
'rgb(153, 102, 255)',
'rgb(255, 205, 86)',
'rgb(54, 162, 235)',
'rgb(75, 192, 192)'
]
if not os.path.isdir("cache/"):
print("not a dir")
os.makedirs("cache/")
cacheFileName = "cache/FRC Grapher JSON Cache " + \
datetime.datetime.now().strftime("%Y-%m-%d %I.%M.%S %p") + ".json"
def valueChanged(table, key, value, isNew):
global currentTimestamp
if key == 'frc-grapher-timestamp':
currentTimestamp = value
for connection in connections:
connection.sendMessage(
u"" + json.dumps({'key': str(key), 'value': str(value)}))
if key in keys:
for connection in connections:
connection.sendMessage(
u"" + json.dumps({'key': str(key), 'value': str(value)}))
if not key in datasets:
color = len(datasets) % len(colors)
datasets[key] = {
"label": key,
"fill": False,
"backgroundColor": colors[color],
"borderColor": colors[color],
"data": [{
"x": currentTimestamp,
"y": value
}]
}
else:
if (datasets[key]["data"][len(datasets[key]["data"]) - 1]["x"] == currentTimestamp):
datasets[key]["data"][len(
datasets[key]["data"]) - 1]["y"] = value
else:
datasets[key]["data"].append({
"x": currentTimestamp,
"y": value
})
with open(cacheFileName, "w") as outfile:
json.dump(datasets, outfile)
def connectionListener(connected, info):
print(info, '; Connected=%s' % connected)
if not args.replay_match:
logging.basicConfig(level=logging.DEBUG)
NetworkTables.initialize(server=args.ip)
NetworkTables.addConnectionListener(
connectionListener, immediateNotify=True)
sd = NetworkTables.getTable("SmartDashboard")
sd.addEntryListener(valueChanged)
def close_sig_handler(signal, frame):
server.close()
sys.exit()
signal.signal(signal.SIGINT, close_sig_handler)
server.serveforever()