Search in sources :

Example 6 with Edge

use of io.openems.backend.metadata.api.Edge 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());
            }
        }
    }
}
Also used : Role(io.openems.common.session.Role) User(io.openems.backend.metadata.api.User) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) Edge(io.openems.backend.metadata.api.Edge)

Example 7 with Edge

use of io.openems.backend.metadata.api.Edge in project openems by OpenEMS.

the class Odoo method authenticate.

/**
 * Tries to authenticate at the Odoo server using a sessionId from a cookie.
 *
 * @param sessionId
 * @return
 * @throws OpenemsException
 */
@Override
public User authenticate(String sessionId) throws OpenemsException {
    HttpURLConnection connection = null;
    try {
        // send request to Odoo
        String charset = "US-ASCII";
        String query = String.format("session_id=%s", URLEncoder.encode(sessionId, charset));
        connection = (HttpURLConnection) new URL(this.url + "/openems_backend/info?" + query).openConnection();
        // 5 secs
        connection.setConnectTimeout(5000);
        // 5 secs
        connection.setReadTimeout(5000);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("{}");
        out.flush();
        out.close();
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            JsonObject j = (new JsonParser()).parse(line).getAsJsonObject();
            if (j.has("error")) {
                JsonObject jError = JsonUtils.getAsJsonObject(j, "error");
                String errorMessage = JsonUtils.getAsString(jError, "message");
                throw new OpenemsException("Odoo replied with error: " + errorMessage);
            }
            if (j.has("result")) {
                // parse the result
                JsonObject jResult = JsonUtils.getAsJsonObject(j, "result");
                JsonObject jUser = JsonUtils.getAsJsonObject(jResult, "user");
                User user = new // 
                User(// 
                JsonUtils.getAsInt(jUser, "id"), JsonUtils.getAsString(jUser, "name"));
                JsonArray jDevices = JsonUtils.getAsJsonArray(jResult, "devices");
                for (JsonElement jDevice : jDevices) {
                    int edgeId = JsonUtils.getAsInt(jDevice, "id");
                    Optional<Edge> edgeOpt = this.getEdgeOpt(edgeId);
                    if (edgeOpt.isPresent()) {
                        Edge edge = edgeOpt.get();
                        synchronized (this.edges) {
                            this.edges.putIfAbsent(edge.getId(), edge);
                        }
                    }
                    user.addEdgeRole(edgeId, Role.getRole(JsonUtils.getAsString(jDevice, "role")));
                }
                synchronized (this.users) {
                    this.users.put(user.getId(), user);
                }
                return user;
            }
        }
        throw new OpenemsException("No matching user found");
    } catch (IOException e) {
        throw new OpenemsException("IOException while reading from Odoo: " + e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : User(io.openems.backend.metadata.api.User) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) IOException(java.io.IOException) URL(java.net.URL) JsonArray(com.google.gson.JsonArray) HttpURLConnection(java.net.HttpURLConnection) JsonElement(com.google.gson.JsonElement) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Edge(io.openems.backend.metadata.api.Edge) JsonParser(com.google.gson.JsonParser)

Example 8 with Edge

use of io.openems.backend.metadata.api.Edge in project openems by OpenEMS.

the class Odoo method getEdgeForceRefresh.

/**
 * Reads the Edge object from Odoo and stores it in the cache
 *
 * @param edgeId
 * @return
 */
private Optional<Edge> getEdgeForceRefresh(int edgeId) {
    try {
        Map<String, Object> edgeMap = OdooUtils.readOne(this.url, this.database, this.uid, this.password, "fems.device", edgeId, Field.FemsDevice.NAME, Field.FemsDevice.COMMENT, Field.FemsDevice.PRODUCT_TYPE, Field.FemsDevice.OPENEMS_CONFIG);
        Object configObj = edgeMap.get(Field.FemsDevice.OPENEMS_CONFIG.n());
        JsonObject jConf;
        if (configObj != null && configObj instanceof String) {
            jConf = JsonUtils.getAsJsonObject(JsonUtils.parse((String) configObj));
        } else {
            jConf = new JsonObject();
        }
        Edge edge = new // 
        Edge(// 
        (Integer) edgeMap.get(Field.FemsDevice.ID.n()), // 
        (String) edgeMap.get(Field.FemsDevice.NAME.n()), // 
        (String) edgeMap.get(Field.FemsDevice.COMMENT.n()), // 
        (String) edgeMap.get(Field.FemsDevice.PRODUCT_TYPE.n()), jConf);
        edge.onSetConfig(jConfig -> {
            // Update Edge config in Odoo
            String config = new GsonBuilder().setPrettyPrinting().create().toJson(jConfig);
            this.write(edge, new FieldValue(Field.FemsDevice.OPENEMS_CONFIG, config));
        });
        edge.onSetLastMessage(() -> {
            // Set LastMessage timestamp in Odoo
            this.writeWorker.onLastMessage(edgeId);
        });
        edge.onSetLastUpdate(() -> {
            // Set LastUpdate timestamp in Odoo
            this.writeWorker.onLastUpdate(edgeId);
        });
        edge.onSetSoc(soc -> {
            // Set SoC in Odoo
            this.write(edge, new FieldValue(Field.FemsDevice.SOC, String.valueOf(soc)));
        });
        edge.onSetIpv4(ipv4 -> {
            // Set IPv4 in Odoo
            this.write(edge, new FieldValue(Field.FemsDevice.IPV4, String.valueOf(ipv4)));
        });
        edge.setOnline(this.edgeWebsocketService.isOnline(edge.getId()));
        // store in cache
        synchronized (this.edges) {
            this.edges.put(edge.getId(), edge);
        }
        return Optional.ofNullable(edge);
    } catch (OpenemsException e) {
        log.error("Unable to read Edge [ID:" + edgeId + "]: " + e.getMessage());
        return Optional.empty();
    }
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) JsonObject(com.google.gson.JsonObject) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) Edge(io.openems.backend.metadata.api.Edge)

Example 9 with Edge

use of io.openems.backend.metadata.api.Edge in project openems by OpenEMS.

the class EdgeWebsocketServer method _onMessage.

/**
 * Message event of websocket. Handles a new message. At this point the Edge is
 * already authenticated.
 */
@Override
protected void _onMessage(WebSocket websocket, JsonObject jMessage) {
    // get edgeIds from websocket
    int[] edgeIds = websocket.getAttachment();
    // set last update timestamps in MetadataService
    for (int edgeId : edgeIds) {
        Optional<Edge> edgeOpt = this.parent.metadataService.getEdgeOpt(edgeId);
        if (edgeOpt.isPresent()) {
            Edge edge = edgeOpt.get();
            edge.setLastMessage();
        }
    }
    // get MessageId from message
    JsonObject jMessageId = JsonUtils.getAsOptionalJsonObject(jMessage, "messageId").orElse(new JsonObject());
    /*
		 * Config? -> store in Metadata
		 */
    Optional<JsonObject> jConfigOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "config");
    if (jConfigOpt.isPresent()) {
        JsonObject jConfig = jConfigOpt.get();
        for (int edgeId : edgeIds) {
            Edge edge;
            try {
                edge = this.parent.metadataService.getEdge(edgeId);
                edge.setConfig(jConfig);
            } catch (OpenemsException e) {
                WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.METADATA_ERROR, e.getMessage());
            }
        }
        return;
    }
    /*
		 * Is this a reply? -> forward to UI
		 */
    if (jMessage.has("messageId")) {
        for (int edgeId : edgeIds) {
            try {
                this.parent.uiWebsocketService.handleEdgeReply(edgeId, jMessage);
            } catch (OpenemsException e) {
                WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_UNABLE_TO_FORWARD, "ID:" + edgeId, e.getMessage());
            }
        }
        return;
    }
    /*
		 * New timestamped data
		 */
    Optional<JsonObject> jTimedataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "timedata");
    if (jTimedataOpt.isPresent()) {
        timedata(edgeIds, jTimedataOpt.get());
        return;
    }
    /*
		 * Unknown message
		 */
    for (String edgeName : getEdgeNames(edgeIds)) {
        WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.UNKNOWN_MESSAGE, edgeName, StringUtils.toShortString(jMessage, 100));
    }
}
Also used : JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) Edge(io.openems.backend.metadata.api.Edge)

Example 10 with Edge

use of io.openems.backend.metadata.api.Edge in project openems by OpenEMS.

the class Dummy method getEdgeOpt.

@Override
public Optional<Edge> getEdgeOpt(int edgeId) {
    Edge edge = this.edges.get(edgeId);
    if (edge == null) {
        int id = this.nextEdgeId++;
        edge = new Edge(id, "EDGE:" + id, "comment [" + id + "]", "producttype [" + id + "]", 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(id, edge);
    }
    return Optional.of(edge);
}
Also used : JsonObject(com.google.gson.JsonObject) Edge(io.openems.backend.metadata.api.Edge)

Aggregations

Edge (io.openems.backend.metadata.api.Edge)10 JsonObject (com.google.gson.JsonObject)9 OpenemsException (io.openems.common.exceptions.OpenemsException)8 JsonElement (com.google.gson.JsonElement)3 User (io.openems.backend.metadata.api.User)3 JsonArray (com.google.gson.JsonArray)2 Role (io.openems.common.session.Role)2 GsonBuilder (com.google.gson.GsonBuilder)1 JsonParser (com.google.gson.JsonParser)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 HashMap (java.util.HashMap)1 TreeMap (java.util.TreeMap)1 UUID (java.util.UUID)1 InfluxDB (org.influxdb.InfluxDB)1