use of io.openems.common.session.Role in project openems by OpenEMS.
the class ChannelDoc method getAsJsonObject.
public JsonObject getAsJsonObject() {
JsonObject j = new JsonObject();
j.addProperty("name", this.name);
j.addProperty("title", this.title);
j.addProperty("description", this.description);
if (typeOpt.isPresent()) {
Class<?> type = this.typeOpt.get();
if (ThingMap.class.isAssignableFrom(type)) {
// for ThingMap type: get the types from annotation and return JsonArray
IsThingMap isThingMapAnnotation = type.getAnnotation(IsThingMap.class);
j.add("type", InjectionUtils.getImplementsAsJson(isThingMapAnnotation.type()));
} else if (DeviceNature.class.isAssignableFrom(type)) {
// for DeviceNatures add complete class name
j.addProperty("type", type.getCanonicalName());
} else {
// for simple types, use only simple name (e.g. 'Long', 'Integer',...)
j.addProperty("type", type.getSimpleName());
}
}
j.addProperty("optional", this.optional);
j.addProperty("array", this.array);
JsonArray jReadRoles = new JsonArray();
for (Role role : this.readRoles) {
jReadRoles.add(role.name().toLowerCase());
}
j.add("readRoles", jReadRoles);
JsonArray jWriteRoles = new JsonArray();
for (Role role : this.writeRoles) {
jWriteRoles.add(role.name().toLowerCase());
}
j.add("writeRoles", jWriteRoles);
j.addProperty("defaultValue", this.defaultValue);
j.addProperty("jsonSchema", this.jsonSchema);
return j;
}
use of io.openems.common.session.Role in project openems by OpenEMS.
the class EdgeWebsocketHandler method onMessage.
/**
* Handles a message from Websocket.
*
* @param jMessage
*/
public final void onMessage(JsonObject jMessage) {
if (!this.userOpt.isPresent()) {
log.error("No User! Aborting...");
return;
}
Role role = this.userOpt.get().getRole();
// get MessageId from message -> used for reply
Optional<JsonObject> jMessageIdOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "messageId");
if (jMessageIdOpt.isPresent()) {
JsonObject jMessageId = jMessageIdOpt.get();
/*
* Config
*/
Optional<JsonObject> jConfigOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "config");
if (jConfigOpt.isPresent()) {
this.config(role, jMessageId, apiWorkerOpt, jConfigOpt.get());
return;
}
/*
* Subscribe to currentData
*/
Optional<JsonObject> jCurrentDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "currentData");
if (jCurrentDataOpt.isPresent()) {
this.currentData(jMessageId, jCurrentDataOpt.get());
return;
}
/*
* Query historic data
*/
Optional<JsonObject> jhistoricDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "historicData");
if (jhistoricDataOpt.isPresent()) {
this.historicData(jMessageId, jhistoricDataOpt.get());
return;
}
/*
* Subscribe to log
*/
Optional<JsonObject> jLogOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "log");
if (jLogOpt.isPresent()) {
try {
this.log(role, jMessageId, jLogOpt.get());
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.UNABLE_TO_SUBSCRIBE_TO_LOG, e.getMessage());
}
}
/*
* Remote system control
*/
Optional<JsonObject> jSystemOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "system");
if (jSystemOpt.isPresent()) {
try {
this.system(jMessageId, jSystemOpt.get(), role);
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.UNABLE_TO_EXECUTE_SYSTEM_COMMAND, e.getMessage());
}
}
}
}
use of io.openems.common.session.Role in project openems by OpenEMS.
the class UiWebsocketServer method _onOpen.
@Override
protected void _onOpen(WebSocket websocket, ClientHandshake handshake) {
User user;
// login using session_id from the cookie
Optional<String> sessionIdOpt = getFieldFromHandshakeCookie(handshake, "session_id");
try {
if (sessionIdOpt.isPresent()) {
// authenticate with Session-ID
user = this.parent.metadataService.authenticate(sessionIdOpt.get());
} else {
// authenticate without Session-ID
user = this.parent.metadataService.authenticate();
}
} catch (OpenemsException e) {
// send connection failed to browser
WebSocketUtils.sendOrLogError(websocket, DefaultMessages.uiLogoutReply());
log.warn("User connection failed. Session [" + sessionIdOpt.orElse("") + "] Error [" + e.getMessage() + "].");
websocket.closeConnection(CloseFrame.REFUSE, e.getMessage());
return;
}
UUID uuid = UUID.randomUUID();
synchronized (this.websocketsMap) {
// add websocket to local cache
this.websocketsMap.put(uuid, websocket);
}
// store userId together with the websocket
websocket.setAttachment(new WebsocketData(user.getId(), uuid));
// send connection successful to browser
JsonArray jEdges = new JsonArray();
for (Entry<Integer, Role> edgeRole : user.getEdgeRoles().entrySet()) {
int edgeId = edgeRole.getKey();
Role role = edgeRole.getValue();
Edge edge;
try {
edge = this.parent.metadataService.getEdge(edgeId);
JsonObject jEdge = edge.toJsonObject();
jEdge.addProperty("role", role.toString());
jEdges.add(jEdge);
} catch (OpenemsException e) {
log.warn("Unable to get Edge from MetadataService [ID:" + edgeId + "]: " + e.getMessage());
}
}
log.info("User [" + user.getName() + "] connected with Session [" + sessionIdOpt.orElse("") + "].");
JsonObject jReply = DefaultMessages.uiLoginSuccessfulReply("", /* empty token? */
jEdges);
WebSocketUtils.sendOrLogError(websocket, jReply);
}
use of io.openems.common.session.Role in project openems by OpenEMS.
the class File method refreshData.
private void refreshData() {
if (this.edges.isEmpty()) {
try {
// read file
FileReader fr = new FileReader(this.path);
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
try {
String[] parameters = s.split(";");
String name = parameters[0];
String comment = parameters[1];
String producttype = parameters[2];
Role role = Role.getRole(parameters[3]);
int edgeId = Integer.parseInt(parameters[4]);
String apikey = parameters[5];
MyEdge edge = new MyEdge(edgeId, name, comment, producttype, role, apikey, new JsonObject());
edge.onSetConfig(jConfig -> {
log.debug("Edge [" + edgeId + "]. Update config: " + StringUtils.toShortString(jConfig, 100));
});
edge.onSetSoc(soc -> {
log.debug("Edge [" + edgeId + "]. Set SoC: " + soc);
});
edge.onSetIpv4(ipv4 -> {
log.debug("Edge [" + edgeId + "]. Set IPv4: " + ipv4);
});
edge.setOnline(this.edgeWebsocketService.isOnline(edge.getId()));
this.edges.put(edgeId, edge);
} catch (Throwable e) {
log.error("Unable to parse line [" + s + "]. " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
fr.close();
} catch (IOException e) {
log.error("Unable to read file [" + this.path + "]: " + e.getMessage());
}
// refresh user
this.user = new User(0, "admin");
for (int edgeId : this.edges.keySet()) {
this.user.addEdgeRole(edgeId, Role.ADMIN);
}
}
}
use of io.openems.common.session.Role in project openems by OpenEMS.
the class UiWebsocketServer method _onMessage.
@Override
protected void _onMessage(WebSocket websocket, JsonObject jMessage) {
// get current User
WebsocketData data = websocket.getAttachment();
int userId = data.getUserId();
Optional<User> userOpt = this.parent.metadataService.getUser(userId);
if (!userOpt.isPresent()) {
WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), LogBehaviour.WRITE_TO_LOG, Notification.BACKEND_UNABLE_TO_READ_USER_DETAILS, userId);
return;
}
User user = userOpt.get();
// get MessageId from message
Optional<JsonObject> jMessageIdOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "messageId");
// get EdgeId from message
Optional<Integer> edgeIdOpt = JsonUtils.getAsOptionalInt(jMessage, "edgeId");
if (jMessageIdOpt.isPresent() && edgeIdOpt.isPresent()) {
JsonObject jMessageId = jMessageIdOpt.get();
int edgeId = edgeIdOpt.get();
// get Edge
Edge edge;
try {
edge = this.parent.metadataService.getEdge(edgeId);
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.BACKEND_UNABLE_TO_READ_EDGE_DETAILS, edgeId, e.getMessage());
return;
}
/*
* verify that User is allowed to access Edge
*/
if (!user.getEdgeRole(edgeId).isPresent()) {
WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.BACKEND_FORWARD_TO_EDGE_NOT_ALLOWED, edge.getName(), user.getName());
return;
}
/*
* Query historic data
*/
Optional<JsonObject> jHistoricDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "historicData");
if (jHistoricDataOpt.isPresent()) {
JsonObject jHistoricData = jHistoricDataOpt.get();
log.info("User [" + user.getName() + "] queried historic data for Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jHistoricData, 50));
this.historicData(websocket, jMessageId, edgeId, jHistoricData);
return;
}
/*
* Subscribe to currentData
*/
Optional<JsonObject> jCurrentDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "currentData");
if (jCurrentDataOpt.isPresent()) {
JsonObject jCurrentData = jCurrentDataOpt.get();
log.info("User [" + user.getName() + "] subscribed to current data for Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jCurrentData, 50));
this.currentData(websocket, data, jMessageId, edgeId, jCurrentData);
return;
}
/*
* Serve "Config -> Query" from cache
*/
Optional<JsonObject> jConfigOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "config");
if (jConfigOpt.isPresent()) {
JsonObject jConfig = jConfigOpt.get();
switch(JsonUtils.getAsOptionalString(jConfig, "mode").orElse("")) {
case "query":
/*
* Query current config
*/
log.info("User [" + user.getName() + "] queried config for Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jConfig, 50));
JsonObject jReply = DefaultMessages.configQueryReply(jMessageId, edge.getConfig());
WebSocketUtils.sendOrLogError(websocket, jReply);
return;
}
}
/*
* Forward to OpenEMS Edge
*/
if (jMessage.has("config") || jMessage.has("log") || jMessage.has("system")) {
try {
log.info("User [" + user.getName() + "] forward message to Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jMessage, 100));
Optional<Role> roleOpt = user.getEdgeRole(edgeId);
JsonObject j = DefaultMessages.prepareMessageForForwardToEdge(jMessage, data.getUuid(), roleOpt);
this.parent.edgeWebsocketService.forwardMessageFromUi(edgeId, j);
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_UNABLE_TO_FORWARD, edge.getName(), e.getMessage());
}
}
}
}
Aggregations