Search in sources :

Example 31 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class TimelineChargeController method higherSoc.

private Map.Entry<LocalTime, Integer> higherSoc(JsonArray jHours, LocalTime time) throws ConfigException {
    // fill times map; sorted by hour
    try {
        TreeMap<LocalTime, Integer> times = new TreeMap<>();
        for (JsonElement jHourElement : jHours) {
            JsonObject jHour = JsonUtils.getAsJsonObject(jHourElement);
            String hourTime = JsonUtils.getAsString(jHour, "time");
            int jsoc = JsonUtils.getAsInt(jHourElement, "soc");
            times.put(LocalTime.parse(hourTime), jsoc);
        }
        // return matching controllers
        if (times.higherEntry(time) != null) {
            return times.higherEntry(time);
        } else {
            throw new IndexOutOfBoundsException("No smaller time found");
        }
    } catch (OpenemsException e) {
        throw new ConfigException("cant read config", e);
    }
}
Also used : LocalTime(java.time.LocalTime) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) ConfigException(io.openems.api.exception.ConfigException) OpenemsException(io.openems.common.exceptions.OpenemsException) TreeMap(java.util.TreeMap)

Example 32 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class Influx method getInfluxDbConnection.

private synchronized InfluxDB getInfluxDbConnection() throws OpenemsException {
    if (!this.influxDbOpt.isPresent()) {
        InfluxDB influxDB = InfluxDBFactory.connect("http://" + url + ":" + port, username, password);
        try {
            influxDB.ping();
            this.influxDbOpt = Optional.of(influxDB);
        } catch (RuntimeException e) {
            throw new OpenemsException("Unable to connect to InfluxDB: " + e.getMessage());
        }
    }
    return this.influxDbOpt.get();
}
Also used : InfluxDB(org.influxdb.InfluxDB) OpenemsException(io.openems.common.exceptions.OpenemsException)

Example 33 with OpenemsException

use of io.openems.common.exceptions.OpenemsException 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 34 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class UiWebsocketServer method currentData.

/**
 * Handle current data subscriptions
 *
 * @param j
 */
private synchronized void currentData(WebSocket websocket, WebsocketData data, JsonObject jMessageId, int edgeId, JsonObject jCurrentData) {
    try {
        String mode = JsonUtils.getAsString(jCurrentData, "mode");
        if (mode.equals("subscribe")) {
            /*
				 * Subscribe to channels
				 */
            // remove old worker if it existed
            Optional<BackendCurrentDataWorker> workerOpt = data.getCurrentDataWorker();
            if (workerOpt.isPresent()) {
                data.setCurrentDataWorker(null);
                workerOpt.get().dispose();
            }
            // set new worker
            JsonObject jSubscribeChannels = JsonUtils.getAsJsonObject(jCurrentData, "channels");
            BackendCurrentDataWorker worker = new BackendCurrentDataWorker(this, websocket, edgeId);
            worker.setChannels(jSubscribeChannels, jMessageId);
            data.setCurrentDataWorker(worker);
        }
    } catch (OpenemsException e) {
        WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.SUBSCRIBE_CURRENT_DATA_FAILED, "Edge [ID:" + edgeId + "] " + e.getMessage());
    }
}
Also used : JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException)

Example 35 with OpenemsException

use of io.openems.common.exceptions.OpenemsException 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)

Aggregations

OpenemsException (io.openems.common.exceptions.OpenemsException)52 JsonObject (com.google.gson.JsonObject)25 JsonElement (com.google.gson.JsonElement)11 Edge (io.openems.backend.metadata.api.Edge)8 HashMap (java.util.HashMap)8 JsonArray (com.google.gson.JsonArray)7 Channel (io.openems.api.channel.Channel)7 ConfigChannel (io.openems.api.channel.ConfigChannel)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 WriteChannel (io.openems.api.channel.WriteChannel)4 User (io.openems.api.security.User)4 Role (io.openems.common.session.Role)4 WriteJsonObject (io.openems.core.utilities.api.WriteJsonObject)4 JsonParser (com.google.gson.JsonParser)3 ChannelDoc (io.openems.api.doc.ChannelDoc)3 ConfigException (io.openems.api.exception.ConfigException)3 User (io.openems.backend.metadata.api.User)3 Map (java.util.Map)3 UUID (java.util.UUID)3