forked from FIRST-Tech-Challenge/FtcRobotController
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebInterface.java
More file actions
214 lines (174 loc) · 7.66 KB
/
WebInterface.java
File metadata and controls
214 lines (174 loc) · 7.66 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
package org.firstinspires.ftc.teamcode;
//import com.qualcomm.robotcore.util.WebServer;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.nio.channels.ServerSocketChannel;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
enum Mode {
INITIALIZE,
LISTEN
}
public class WebInterface implements Runnable {
ServerSocket serverSocket;
Map<String, Double> parameters;
Mode mode; // prevent calling addParameter after listen is called, for thread safety
int port = 8081;
@Override
public void run() {
try {
System.out.print("Listening on port");
System.out.println(this.port);
listen(this.port);
} catch (IOException e) {
System.out.print("Uh oh:");
System.out.println(e.getMessage());
}
}
WebInterface(int port) {
this.parameters = new HashMap<String, Double>();
this.mode = Mode.INITIALIZE;
this.port = port;
}
public void addParameter(String key, double defaultValue) {
if (this.mode != Mode.INITIALIZE) return;
parameters.put(key, defaultValue);
}
// TODO: fix this because it could crash due to multithreading conflicts if this is set after the server is started
public void setParameter(String key, double value) {
parameters.put(key, value);
}
public void addParameter(String key) {
if (this.mode != Mode.INITIALIZE) return;
parameters.put(key, 0.0);
}
public Double getParameter(String key) {
return parameters.get(key);
}
public void stop() {
try {
System.out.println("Stopping web interface...");
this.serverSocket.close(); // TODO: make this more graceful
} catch (IOException e) {
System.out.print("Uh oh when stopping server (.stop()):");
System.out.println(e.getMessage());
}
}
private void listen(int port) throws IOException {
this.mode = Mode.LISTEN;
this.serverSocket = new ServerSocket(port);
while (true) {
try {
Socket client = this.serverSocket.accept();
handleConnection(client);
client.close();
} catch (Exception e) {
// System.out.println("WebInterface connection error " + e.getMessage());
// e.printStackTrace(); // Helpful to see what actually happened in logcat
}
}
}
private void handleConnection(Socket client) throws IOException {
System.out.println("New connection");
BufferedReader d = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
//.readUTF(); // oops this is modified utf-8 apparently
// oops this was not reading all lines (it just saved all lines that have been sent so far, 0 in my testing, as it's called almost instantly after the connection is started)
// String request = d.toString();
// String[] lines = request.split("(\r\n)|\n");
// read all lines:
ArrayList<String> linesar = new ArrayList<>();
String line;
while ((line = d.readLine()) != null && !line.isEmpty()) {
linesar.add(line);
}
String[] lines = linesar.toArray(new String[0]);
String requestLine = lines[0];
System.out.print("Req: ");
System.out.println(requestLine);
Pattern pattern = Pattern.compile("([A-Z]+) ([^\\s\\r\\n]+) ([^\\s\\r\\n]+).+");
Matcher matched = pattern.matcher(requestLine);
if (!matched.matches()) {
System.out.println("Parsing failed, no match.");
String response = "HTTP/1.1 400 Bad Request\r\n\r\nparsing failed";
DataOutputStream o = new DataOutputStream(client.getOutputStream());
o.write(response.getBytes(StandardCharsets.UTF_8));
o.flush();
System.out.println("sent failure response");
return;
}
String method = matched.group(1);
String route = matched.group(2);
String protocol = matched.group(3);
// String[] headers = Arrays.copyOfRange(lines, 1, lines.length);
String[] headers = {}; // temporarily disabled because it was crashing here I think
String response = handleRoute(route, method, protocol, headers);
DataOutputStream o = new DataOutputStream(client.getOutputStream());
o.write(response.getBytes(StandardCharsets.UTF_8));
o.flush();
System.out.println("sent response, done.");
}
private String handleRoute(String route, String method, String protocol, String[] headers) {
String[] bla = route.split("\\?", 2);
String justRoute = bla[0];
String search = bla.length > 1 ? bla[1] : "";
if (method.equals("GET")) {
switch (justRoute) {
case "/":
return "HTTP/1.1 200 OK\r\n\r\n" + indexHTML();
case "/test":
return "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Type: application/json\r\n\r\nSERVER OK";
case "/getSliders":
return "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Type: text/plain\r\n\r\n" + getSliderJSON();
case "/setValue":
String[] split = search.split(":");
if (split.length < 2) {
return "HTTP/1.1 400 Bad Request\r\n\r\n";
}
parameters.put(split[0], Double.parseDouble(split[1]));
System.out.print("Set parameter ");
System.out.print(split[0]);
System.out.print(" to ");
System.out.println(Double.parseDouble(split[1]));
return "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\n\r\n";
default:
return "HTTP/1.1 404 Not Found\r\n\r\n";
}
}
return "HTTP/1.1 400 Bad Request\r\n\r\n";
}
private String getSliderJSON() {
String sliderArray = "[";
for (Map.Entry<String, Double> entry : parameters.entrySet()) {
double value = entry.getValue();
String key = entry.getKey();
sliderArray += "[\"" + key + "\", \"" + value + "\"],";
}
return sliderArray + "]";
}
private String indexHTML() {
String sliders = "";
String sliderArray = "[";
for (Map.Entry<String, Double> entry : parameters.entrySet()) {
double value = entry.getValue();
String key = entry.getKey();
sliders += String.format("<label>%s:</label><input id=\"%s\" type=\"range\" min=\"0.0\" max=\"2.0\" step=\"0.01\" value=\"%f\" /><label id=\"%s_l\">%f</label><br/>", key, key, value, key, value);
sliderArray += "\"" + key + "\",";
}
String js = sliderArray + "].forEach( key => document.getElementById(key).addEventListener('input', (ev) => { document.getElementById(key+'_l').innerText=ev.target.value; fetch('/setValue?'+ev.target.id+':'+ev.target.value) }));";
return "<!DOCTYPE html><html lang=\"en\"><head><title>FTC Web Interface</title></head><body>\n"
+ sliders
+"<canvas id=\"canvas\" width=\"800\" height=\"450\"></canvas>"
+"<script>" + js + "</script></body></html>";
}
}