Search in sources :

Example 1 with OpenemsException

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

the class StuderConnection method execute.

public void execute() throws OpenemsException {
    try {
        if (connection != null && connection.isOpen() && request != null) {
            OutputStream out = connection.getOutputStream();
            for (byte b : request.getBytes()) {
                out.write(b);
            }
            out.flush();
            out.close();
            InputStream in = connection.getInputStream();
            byte startByte = (byte) in.read();
            if (startByte == (byte) 0xAA) {
                List<Byte> checksumBytes = new ArrayList<>();
                byte frameTags = (byte) in.read();
                boolean isMessagePending = (frameTags & 1) != 0;
                boolean isRccRestart = (frameTags & 2) != 0;
                boolean isSdCardPresent = (frameTags & 4) != 0;
                boolean isSdCardFull = (frameTags & 8) != 0;
                boolean isNewDataloggerFilePresent = (frameTags & 16) != 0;
                boolean isDatalogSupported = (frameTags & 32) != 0;
                checksumBytes.add(frameTags);
                byte[] srcAddressBytes = new byte[4];
                for (int i = 0; i < 4; i++) {
                    byte b = (byte) in.read();
                    srcAddressBytes[i] = b;
                    checksumBytes.add(b);
                }
                int srcAddress = ByteBuffer.wrap(srcAddressBytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
                byte[] dstAddressBytes = new byte[4];
                for (int i = 0; i < 4; i++) {
                    byte b = (byte) in.read();
                    dstAddressBytes[i] = b;
                    checksumBytes.add(b);
                }
                int dstAddress = ByteBuffer.wrap(dstAddressBytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
                byte[] dataLengthBytes = new byte[2];
                for (int i = 0; i < 2; i++) {
                    byte b = (byte) in.read();
                    dataLengthBytes[i] = b;
                    checksumBytes.add(b);
                }
                short dataLength = ByteBuffer.wrap(dataLengthBytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
                byte[] headerChecksumBytes = new byte[2];
                for (int i = 0; i < 2; i++) {
                    byte b = (byte) in.read();
                    headerChecksumBytes[i] = b;
                }
                List<Byte> calculatedHeaderChecksum = Service.calculateChecksum(checksumBytes);
                if (headerChecksumBytes[0] == calculatedHeaderChecksum.get(0) && headerChecksumBytes[1] == calculatedHeaderChecksum.get(1)) {
                    byte[] dataBytes = new byte[dataLength];
                    checksumBytes.clear();
                    for (int i = 0; i < dataLength; i++) {
                        byte b = (byte) in.read();
                        dataBytes[i] = b;
                        checksumBytes.add(b);
                    }
                    byte[] dataChecksumBytes = new byte[2];
                    dataChecksumBytes[0] = (byte) in.read();
                    dataChecksumBytes[1] = (byte) in.read();
                    List<Byte> calculatedDataChecksum = Service.calculateChecksum(checksumBytes);
                    if (dataChecksumBytes[0] == calculatedDataChecksum.get(0) && dataChecksumBytes[1] == calculatedDataChecksum.get(1)) {
                        ByteBuffer buffer = ByteBuffer.wrap(dataBytes).order(ByteOrder.LITTLE_ENDIAN);
                        byte dataFlagsByte = dataBytes[0];
                        boolean isError = (dataFlagsByte & 1) != 0;
                        boolean isResponse = (dataFlagsByte & 2) != 0;
                        byte serviceIdByte = dataBytes[1];
                        ObjectType objectType = ObjectType.getByCode(buffer.getShort(2));
                        int objectId = buffer.getInt(4);
                        PropertyId propertyId = PropertyId.getByCode(buffer.getShort(8));
                        if (this.request.getServiceId() != serviceIdByte) {
                            System.out.println("ServiceId of Response is not equals Request ServiceId.");
                        } else {
                            this.request.createResponse(isResponse, isError, isDatalogSupported, isNewDataloggerFilePresent, isSdCardFull, isSdCardPresent, isRccRestart, isMessagePending, srcAddress, dstAddress, objectType, propertyId, objectId, Arrays.copyOfRange(dataBytes, 10, dataBytes.length));
                        }
                    } else {
                        throw new OpenemsException("DataChecksum wrong");
                    }
                } else {
                    throw new OpenemsException("HeaderChecksum wrong");
                }
            } else {
                throw new OpenemsException("Stream start not found.");
            }
            in.close();
        } else {
            throw new OpenemsException("Connection is not open!");
        }
    } catch (IOException e) {
        throw new OpenemsException("IOException: " + e.getMessage());
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) OpenemsException(io.openems.common.exceptions.OpenemsException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PropertyId(io.openems.impl.protocol.studer.internal.object.PropertyId) ObjectType(io.openems.impl.protocol.studer.internal.object.ObjectType)

Example 2 with OpenemsException

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

the class EdgeWebsocketServer method timedata.

private void timedata(int[] edgeIds, JsonObject jTimedata) {
    for (int edgeId : edgeIds) {
        Edge edge;
        try {
            edge = this.parent.metadataService.getEdge(edgeId);
        } catch (OpenemsException e) {
            log.warn(e.getMessage());
            continue;
        }
        /*
			 * write data to timedataService
			 */
        try {
            this.parent.timedataService.write(edgeId, jTimedata);
            log.debug("Edge [" + edge.getName() + "] wrote " + jTimedata.entrySet().size() + " timestamps " + StringUtils.toShortString(jTimedata, 120));
        } catch (Exception e) {
            log.error("Unable to write Timedata: " + e.getClass().getSimpleName() + ": " + e.getMessage());
        }
        for (Entry<String, JsonElement> jTimedataEntry : jTimedata.entrySet()) {
            try {
                JsonObject jChannels = JsonUtils.getAsJsonObject(jTimedataEntry.getValue());
                // set Odoo last update timestamp only for those channels
                for (String channel : jChannels.keySet()) {
                    if (channel.endsWith("ActivePower") || channel.endsWith("ActivePowerL1") | channel.endsWith("ActivePowerL2") | channel.endsWith("ActivePowerL3") | channel.endsWith("Soc")) {
                        edge.setLastUpdate();
                    }
                }
                // set specific Odoo values
                if (jChannels.has("ess0/Soc")) {
                    int soc = JsonUtils.getAsPrimitive(jChannels, "ess0/Soc").getAsInt();
                    edge.setSoc(soc);
                }
                if (jChannels.has("system0/PrimaryIpAddress")) {
                    String ipv4 = JsonUtils.getAsPrimitive(jChannels, "system0/PrimaryIpAddress").getAsString();
                    edge.setIpv4(ipv4);
                }
            } catch (OpenemsException e) {
                log.error("Edgde [" + edge.getName() + "] error: " + e.getMessage());
            }
        }
    }
}
Also used : JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) Edge(io.openems.backend.metadata.api.Edge) OpenemsException(io.openems.common.exceptions.OpenemsException)

Example 3 with OpenemsException

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

the class EdgeWebsocketServer method _onOpen.

/**
 * Open event of websocket. Parses the "apikey" and to authenticate Edge.
 */
@Override
protected void _onOpen(WebSocket websocket, ClientHandshake handshake) {
    String apikey = "";
    try {
        // get apikey from handshake
        Optional<String> apikeyOpt = Utils.parseApikeyFromHandshake(handshake);
        if (!apikeyOpt.isPresent()) {
            throw new OpenemsException("Apikey is missing in handshake");
        }
        apikey = apikeyOpt.get();
        // get edgeId for apikey
        int[] edgeIds = this.parent.metadataService.getEdgeIdsForApikey(apikey);
        // if existing: close existing websocket for this apikey
        synchronized (this.websocketsMap) {
            for (int edgeId : edgeIds) {
                if (this.websocketsMap.containsKey(edgeId)) {
                    WebSocket oldWebsocket = this.websocketsMap.get(edgeId);
                    oldWebsocket.closeConnection(CloseFrame.REFUSE, "Another Edge with this apikey [" + apikey + "] connected.");
                }
                // add websocket to local cache
                this.websocketsMap.put(edgeId, websocket);
            }
        }
        // store edgeIds together with WebSocket
        websocket.setAttachment(edgeIds);
        // send successful reply to openems
        JsonObject jReply = DefaultMessages.openemsConnectionSuccessfulReply();
        WebSocketUtils.send(websocket, jReply);
        // announce Edge as online
        for (int edgeId : edgeIds) {
            Map<String, Object> properties = new HashMap<>();
            properties.put(BackendEventConstants.PROPERTY_KEY_EDGE_ID, edgeId);
            Event event = new Event(BackendEventConstants.TOPIC_EDGE_ONLINE, properties);
            this.parent.eventAdmin.postEvent(event);
        }
        // log
        for (int edgeId : edgeIds) {
            Optional<Edge> edgeOpt = this.parent.metadataService.getEdgeOpt(edgeId);
            if (edgeOpt.isPresent()) {
                Edge edge = edgeOpt.get();
                log.info(// 
                "Edge [" + edge.getName() + "]" + // 
                (edgeIds.length > 1 ? ", ID [" + edgeId + "]" : "") + " connected.");
                // set last update timestamps in MetadataService
                edge.setLastMessage();
            } else {
                log.info("Edge [ID:" + edgeId + "] connected. Apikey [" + apikey + "]. Websocket [" + websocket + "].");
            }
        }
    } catch (OpenemsException e) {
        // send connection failed to OpenEMS
        JsonObject jReply = DefaultMessages.openemsConnectionFailedReply(e.getMessage());
        WebSocketUtils.sendOrLogError(websocket, jReply);
        // close websocket
        websocket.closeConnection(CloseFrame.REFUSE, "Connection to backend failed. Apikey [" + apikey + "]. Error: " + e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) WebSocket(org.java_websocket.WebSocket) Event(org.osgi.service.event.Event) JsonObject(com.google.gson.JsonObject) Edge(io.openems.backend.metadata.api.Edge)

Example 4 with OpenemsException

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

the class ReadProperty method updateValue.

public default void updateValue(int srcAddress, int dstAddress, StuderBridge studerBridge) throws OpenemsException {
    try {
        ReadRequest<T> readRequest = readRequest(srcAddress, dstAddress);
        studerBridge.execute(readRequest);
        ReadResponse<T> response = readRequest.getResponse();
        T value = response.getValue();
        StuderChannel<T> channel = channel();
        if (channel == null) {
            return;
        } else if (channel instanceof StuderReadChannel) {
            ((StuderReadChannel<T>) channel).updateValue(value);
        } else if (channel instanceof StuderWriteChannel) {
            ((StuderWriteChannel<T>) channel).updateValue(value);
        } else {
            throw new OpenemsException("Unable to set value [" + value + "]. Channel [" + channel.address() + "] is no StuderReadChannel or StuderWriteChannel.");
        }
    } catch (IOException e) {
        throw new OpenemsException("Unable to update value", e);
    }
}
Also used : OpenemsException(io.openems.common.exceptions.OpenemsException) IOException(java.io.IOException)

Example 5 with OpenemsException

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

the class TimelineChargeController method floorSoc.

private Entry<LocalTime, Integer> floorSoc(JsonArray jHours, LocalTime time) throws ConfigException {
    try {
        // fill times map; sorted by hour
        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.floorEntry(time) != null) {
            return times.floorEntry(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)

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