Added enums, msgpack - new ui intergration

This commit is contained in:
Omer
2019-10-12 03:38:42 +03:00
parent 2eb4cbc950
commit 5f879f9d98
17 changed files with 239 additions and 193 deletions

View File

@@ -22,11 +22,10 @@ public class Server {
System.out.println("Socket Disconnected");
SettingsManager.saveSettings();
});
ws.onMessage(ctx -> {
// handler.onMessage(ctx);
ws.onBinaryMessage(ctx -> {
handler.onBinaryMessage(ctx);
});
ws.onBinaryMessage(ctx->handler.onMessage(ctx));
app.start(port);
});
app.start(port);
}
}
}

View File

@@ -1,33 +1,33 @@
package com.chameleonvision.web;
import com.chameleonvision.vision.Orientation;
import com.chameleonvision.vision.SortMode;
import com.chameleonvision.vision.TargetGroup;
import com.chameleonvision.vision.TargetIntersection;
import com.chameleonvision.vision.camera.CameraException;
import com.chameleonvision.settings.SettingsManager;
import com.chameleonvision.vision.camera.CameraManager;
import edu.wpi.cscore.VideoException;
import io.javalin.websocket.*;
import org.apache.commons.lang3.ArrayUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.msgpack.MessagePack;
import org.msgpack.template.Templates;
import org.msgpack.type.ArrayValue;
import org.msgpack.type.BooleanValue;
import org.msgpack.type.IntegerValue;
import org.msgpack.type.MapValue;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.ImmutableArrayValue;
import org.msgpack.value.ImmutableValue;
import org.msgpack.value.Value;
import org.springframework.beans.BeanUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
public class ServerHandler {
private static List<WsContext> users;
private MessagePack msgpack;
ServerHandler() {
users = new ArrayList<>();
msgpack = new MessagePack();
}
void onConnect(WsConnectContext context) {
@@ -39,103 +39,97 @@ public class ServerHandler {
users.remove(context);
}
void onMessage(WsBinaryMessageContext data) throws IOException {
byte[] b = ArrayUtils.toPrimitive(data.data());
System.out.println(msgpack.read(b).isMapValue());
Map entries = msgpack.read(b,Templates.tMap(Templates.TString,Templates.TValue));
System.out.println(Arrays.toString(entries.entrySet().toArray()));
entries.forEach((k, value) -> {
/*
To get int from value
((IntegerValue)value).getInt();
To get boolean from value
((BooleanValue)value).getBoolean();
To get Array from value
((ArrayValue) value).toArray();
*/
String key = k.toString();
System.out.printf("Got websocket msgpack data: [%s, %s]\n", key, value);
try{
if (hasField(CameraManager.getCurrentPipeline(), key)) {
//Special cases for exposure and brightness and aspect ratio
switch (key) {
case "exposure":
int newExposure = ((IntegerValue)value).getInt();
System.out.printf("Changing exposure to %d\n", newExposure);
try {
CameraManager.getCurrentCamera().setExposure(newExposure);
} catch (VideoException e) {
System.out.println("Exposure changes is not supported on your webcam/webcam's driver");
}
break;
case "brightness":
int newBrightness = (int) value;
System.out.printf("Changing brightness to %d\n", newBrightness);
CameraManager.getCurrentCamera().setBrightness(newBrightness);
break;
case "ratio":
//If there is any better to convert Integer to Double you're welcome to change it
List<Double> doubleRatio = CameraManager.getCurrentPipeline().ratio;
List<Object> newRatio = ((JSONArray) value).toList();
for (int i = 0; i < newRatio.size(); i++) {
doubleRatio.set(i, Double.parseDouble(newRatio.get(i).toString()));
}
break;
default:
//Any other field in CameraManager that doesn't need anything special
setField(CameraManager.getCurrentPipeline(), key, value);
System.out.println("CameraManager.getCurrentPipeline().hue = " + CameraManager.getCurrentPipeline().hue.get(0));
break;
void onBinaryMessage(WsBinaryMessageContext data) throws Exception {
MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(ArrayUtils.toPrimitive(data.data()));
int length = unpacker.unpackMapHeader();
for (int mapIndex = 0; mapIndex < length; mapIndex++) {
String key = unpacker.unpackString(); // key
Object value = get(unpacker.unpackValue());
try {
if (hasField(CameraManager.getCurrentPipeline(), key)) {
//Special cases for exposure and brightness and aspect ratio
switch (key) {
case "exposure":
int newExposure = (int) value;
System.out.printf("Changing exposure to %d\n", newExposure);
try {
;
CameraManager.getCurrentCamera().setExposure(newExposure);
} catch (VideoException e) {
System.out.println("Exposure changes is not supported on your webcam/webcam's driver");
}
break;
case "brightness":
int newBrightness = (int) value;
System.out.printf("Changing brightness to %d\n", newBrightness);
CameraManager.getCurrentCamera().setBrightness(newBrightness);
break;
case "ratio":
CameraManager.getCurrentPipeline().ratio=getFloatList((ImmutableArrayValue) value);
break;
case "area":
CameraManager.getCurrentPipeline().area=getFloatList((ImmutableArrayValue) value);
break;
//Enums
case "targetIntersection":
setField(CameraManager.getCurrentPipeline(), key, TargetIntersection.values()[(int) value]);
break;
case "targetGroup":
setField(CameraManager.getCurrentPipeline(), key, TargetGroup.values()[(int) value]);
break;
case "sortMode":
setField(CameraManager.getCurrentPipeline(), key, SortMode.values()[(int) value]);
break;
case "orientation":
setField(CameraManager.getCurrentPipeline(), key, Orientation.values()[(int) value]);
break;
default:
//Any other field in CameraManager that doesn't need anything special
setField(CameraManager.getCurrentPipeline(), key, value);
break;
}
} else {
switch (key) {
case "change_general_settings_values":
Map<String, Object> map = (Map<String, Object>) value;
map.forEach((s, o) -> setField(SettingsManager.GeneralSettings, s, o));
SettingsManager.saveSettings();
break;
case "curr_camera":
String newCamera = (String) value;
System.out.printf("Changing camera to %s\n", newCamera);
CameraManager.setCurrentCamera(newCamera);
HashMap<String, Integer> portMap = new HashMap<>();
portMap.put("port", CameraManager.getCurrentCamera().getStreamPort());
sendFullSettings();
break;
case "curr_pipeline":
int newPipeline = (int) value;
System.out.printf("Changing pipeline to %s\n", newPipeline);
CameraManager.setCurrentPipeline(newPipeline);
CameraManager.getCurrentCameraProcess().ntPipelineEntry.setNumber(newPipeline);
broadcastMessage(allFieldsToMap(CameraManager.getCurrentPipeline()));
break;
case "resolution":
int newVideoMode = (int) value;
System.out.printf("Changing video mode to %d\n", newVideoMode);
CameraManager.getCurrentCamera().setCamVideoMode(newVideoMode, true);
break;
case "FOV":
float newFov = ((Integer) value) * 1F;//TODO check this
System.out.printf("Changing FOV to %f\n", newFov);
CameraManager.getCurrentCamera().setFOV(newFov);
break;
default:
System.out.printf("Unexpected value from websocket: [%s, %s]\n", key, value);
break;
}
}
} else {
switch (key) {
case "change_general_settings_values":
Map<String, Object> map = (Map<String, Object>) value;
map.forEach((s, o) -> setField(SettingsManager.GeneralSettings, s, o));
SettingsManager.saveSettings();
break;
case "curr_camera":
String newCamera = (String) value;
System.out.printf("Changing camera to %s\n", newCamera);
CameraManager.setCurrentCamera(newCamera);
HashMap<String, Integer> portMap = new HashMap<>();
portMap.put("port", CameraManager.getCurrentCamera().getStreamPort());
sendFullSettings();
break;
case "curr_pipeline":
int newPipeline = (int) value;
System.out.printf("Changing pipeline to %s\n", newPipeline);
CameraManager.setCurrentPipeline(newPipeline);
CameraManager.getCurrentCameraProcess().ntPipelineEntry.setNumber(newPipeline);
broadcastMessage(allFieldsToMap(CameraManager.getCurrentPipeline()));
break;
case "resolution":
int newVideoMode = (int) value;
System.out.printf("Changing video mode to %d\n", newVideoMode);
CameraManager.getCurrentCamera().setCamVideoMode(newVideoMode, true);
break;
case "FOV":
double newFov = Double.parseDouble(value.toString());//TODO check this
System.out.printf("Changing FOV to %f\n", newFov);
CameraManager.getCurrentCamera().setFOV(newFov);
break;
default:
System.out.printf("Unexpected value from websocket: [%s, %s]\n", key, value);
break;
}}
}
catch (CameraException e)
{
} catch (CameraException e) {
System.err.println("Camera error");
e.printStackTrace();
}
});
broadcastMessage(entries, data);
}
}
private void setField(Object obj, String fieldName, Object value) {
@@ -143,33 +137,64 @@ public class ServerHandler {
Field[] fields = obj.getClass().getFields();
for (Field f : fields) {
if (f.getName().equals(fieldName)) {
if (BeanUtils.isSimpleValueType(value.getClass())) {
if (BeanUtils.isSimpleValueType(f.getType())) {
f.set(obj, value);
} else if (value.getClass() == ArrayValue.class) {
f.set(obj, ((ArrayValue) value).toArray());
} else if (value instanceof ImmutableArrayValue) {
List<Value> valLst = ((ImmutableArrayValue) value).list();
List<Object> lst = new ArrayList<>();
for (Value val : valLst) {
lst.add(get((ImmutableValue) val));
}
f.set(obj, lst);
}
}
}
} catch (IllegalAccessException e) {
System.out.println("IllegalAccessException ");
} catch (Exception e) {
System.out.println("Exception setting field ");
e.printStackTrace();
}
}
private static void broadcastMessage(Object obj, WsContext userToSkip) {//TODO check if session id is a good way to differentiate users
for (var user : users) {
if (userToSkip != null && user.getSessionId().equals(userToSkip.getSessionId())) {
continue;
}
user.send(obj);
// if (obj.getClass() == String.class)
// user.send((String) obj);
// else if (obj.getClass() == HashMap.class)
// user.send(new JSONObject((HashMap<String, Object>) obj).toString());
// else
// user.send(new JSONObject(obj).toString());
private Object get(ImmutableValue v) throws Exception {
//TODO find a smarter way to write this
if (v.isIntegerValue())
return v.asIntegerValue().toInt();
if (v.isFloatValue())
return v.asFloatValue().toFloat();
if (v.isArrayValue()) {
return v.asArrayValue();
}
if (v.isBinaryValue())
return v.asBinaryValue().asByteArray();
if (v.isBooleanValue())
return v.asBooleanValue().getBoolean();
if (v.isMapValue())
return v.asMapValue().map();
if (v.isStringValue())
return v.asStringValue().asString();
throw new Exception("Value not recognized");
}
private List<Float> getFloatList(ImmutableArrayValue arrayValue) {
List<Float> output = new ArrayList<>();
List<Value> values = arrayValue.list();
for (Value v:values) {
if (v.isFloatValue())
output.add(v.asFloatValue().toFloat());
else
output.add((float) v.asIntegerValue().toInt());
}
return output;
}
private static void broadcastMessage(Object obj, WsContext userToSkip) {
if (users != null)
for (var user : users) {
if (userToSkip != null && user.getSessionId().equals(userToSkip.getSessionId())) {
continue;
}
user.send(obj);
}
}
public static void broadcastMessage(Object obj) {//TODO fix sending for msgpack