Skip to content

Commit

Permalink
Merge pull request #15 from ajayyy/new-web-view
Browse files Browse the repository at this point in the history
Switch to sending over websocket instead of saving a file
  • Loading branch information
ajayyy authored Feb 13, 2021
2 parents 8c23a3d + 2167f14 commit 693e917
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 57 deletions.
Binary file added libs/Java-WebSocket-1.5.1-javadoc.jar
Binary file not shown.
Binary file added libs/Java-WebSocket-1.5.1-sources.jar
Binary file not shown.
Binary file added libs/Java-WebSocket-1.5.1-with-dependencies.jar
Binary file not shown.
6 changes: 3 additions & 3 deletions src/uorocketry/basestation/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ public class Main implements ComponentListener, ChangeListener, ActionListener,

/** Whether to update web view JSON file */
public static boolean webView = false;
/** Where the updating Google Earth kml file is stored */
public static final String WEB_VIEW_DATA_LOCATION = "web/data/data.json";
public static int WEBVIEW_PORT = 4534;

/** Used for the web view */
WebViewUpdater webViewUpdater;
Expand Down Expand Up @@ -398,6 +397,7 @@ public void setupGoogleEarth() {
}

public void setupWebView() {
if (webViewUpdater != null) webViewUpdater.close();
webViewUpdater = new WebViewUpdater();
}

Expand Down Expand Up @@ -444,7 +444,7 @@ private void updateUIInternal() {
}

if (webView) {
webViewUpdater.updateJSONFile(allData, minDataIndexes, currentDataIndexes, config.getJSONArray("datasets"), false);
webViewUpdater.sendUpdate(allData, minDataIndexes, currentDataIndexes, config.getJSONArray("datasets"));
}

// Update every chart
Expand Down
66 changes: 50 additions & 16 deletions src/uorocketry/basestation/WebViewUpdater.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package uorocketry.basestation;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.json.JSONArray;
import org.json.JSONObject;

Expand All @@ -17,14 +17,22 @@
* @author Ajay
*
*/
public class WebViewUpdater {
public class WebViewUpdater extends WebSocketServer {

List<WebSocket> connections = new ArrayList<>();

public WebViewUpdater() {
super(new InetSocketAddress(Main.WEBVIEW_PORT));

start();
}

/**
* Generates a json file from the data currentDataIndex
* Generates a json from the data currentDataIndex
*
* @param main
*/
public JSONObject generateJSONFile(List<List<DataHandler>> allData, List<Integer> minDataIndex, List<Integer> currentDataIndex, JSONArray dataSets) {
public JSONObject generateJSON(List<List<DataHandler>> allData, List<Integer> minDataIndex, List<Integer> currentDataIndex, JSONArray dataSets) {
JSONObject coordinateIndexes = dataSets.getJSONObject(0).getJSONObject("coordinateIndexes");

JSONObject jsonObject = new JSONObject();
Expand All @@ -50,26 +58,52 @@ public JSONObject generateJSONFile(List<List<DataHandler>> allData, List<Integer
}

/**
* Updates the JSON file with the data up to currentDataIndex.
* Sends updated data over the websocket channel
*
* @param tableIndex
* @param allData
* @param currentDataIndex
* @param dataSets
* @param secondRun Is this a second run? This is true if it is being run from a task called by this function.
* The task is run to force Google Earth to update the display.
*/
public void updateJSONFile(List<List<DataHandler>> allData, List<Integer> minDataIndex, List<Integer> currentDataIndex, JSONArray dataSets, boolean secondRun) {
JSONObject jsonObject = generateJSONFile(allData, minDataIndex, currentDataIndex, dataSets);
public void sendUpdate(List<List<DataHandler>> allData, List<Integer> minDataIndex, List<Integer> currentDataIndex, JSONArray dataSets) {
JSONObject jsonObject = generateJSON(allData, minDataIndex, currentDataIndex, dataSets);
if (jsonObject == null) return;

String fileContent = jsonObject.toString();

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(Main.WEB_VIEW_DATA_LOCATION), StandardCharsets.UTF_8))) {
writer.write(fileContent);
for (WebSocket connection : connections) {
connection.send(fileContent);
}
}

public void close() {
try {
super.stop();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

connections.clear();
}

@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
connections.add(conn);
}

@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
connections.remove(conn);
}

@Override
public void onMessage(WebSocket conn, String message) { }

@Override
public void onError(WebSocket conn, Exception ex) { }

@Override
public void onStart() { }
}
70 changes: 32 additions & 38 deletions web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -105,47 +105,41 @@

const updateMarkerDiv = document.getElementById("updateMarker");

const updateTime = 50;
const webSocket = new WebSocket("ws://localhost:4534");
webSocket.onopen = console.log;
webSocket.onerror = console.log;

let lastUpdateMarker = Date.now();
while (true) {
webSocket.onmessage = (event) => {
const startTime = Date.now();
const result = await fetch("data/data.json");
if (result.ok) {
try {
const data = await result.json();
const newLocation = new Microsoft.Maps.Location(data.latitude, data.longitude);

map.setView({
center: newLocation
});

pin.setLocation(newLocation);
lineVertices.push(newLocation);
line.setLocations(lineVertices);

altitudeDiv.innerText = "Altitude: " + data.altitude + " m";

// Calculate downrange distance
distanceDiv.innerText = "Distance: " + Microsoft.Maps.SpatialMath.getDistanceTo(lineVertices[0],
newLocation, Microsoft.Maps.SpatialMath.DistanceUnits.Meters) + " m";

if (startTime - lastUpdateMarker > 5000) {
lastUpdateMarker = startTime;
if (updateMarkerDiv.innerText.length === 0) {
updateMarkerDiv.innerText = ".";
} else {
updateMarkerDiv.innerText = "";
}
try {
const data = JSON.parse(event.data);
const newLocation = new Microsoft.Maps.Location(data.latitude, data.longitude);

map.setView({
center: newLocation
});

pin.setLocation(newLocation);
lineVertices.push(newLocation);
line.setLocations(lineVertices);

altitudeDiv.innerText = "Altitude: " + data.altitude + " m";

// Calculate downrange distance
distanceDiv.innerText = "Distance: " + Microsoft.Maps.SpatialMath.getDistanceTo(lineVertices[0],
newLocation, Microsoft.Maps.SpatialMath.DistanceUnits.Meters) + " m";

if (startTime - lastUpdateMarker > 5000) {
lastUpdateMarker = startTime;
if (updateMarkerDiv.innerText.length === 0) {
updateMarkerDiv.innerText = ".";
} else {
updateMarkerDiv.innerText = "";
}
} catch(e) { console.log(e)}
}

const endTime = Date.now();
if (endTime - startTime < updateTime) {
// Wait until updateTime has passed
await new Promise((resolve) => setTimeout(resolve, updateTime - (endTime - startTime)));
}
}
}
} catch(e) { console.log(e)}
};
}
</script>

Expand Down

0 comments on commit 693e917

Please sign in to comment.