Search in sources :

Example 21 with OpenemsException

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

the class Influx method write.

/**
 * Takes a JsonObject and writes the points to influxDB.
 *
 * Format: { "timestamp1" { "channel1": value, "channel2": value }, "timestamp2"
 * { "channel1": value, "channel2": value } }
 */
@Override
public void write(int edgeId, JsonObject jData) throws OpenemsException {
    Edge edge = this.metadataService.getEdge(edgeId);
    int influxId = InfluxdbUtils.parseNumberFromName(edge.getName());
    TreeBasedTable<Long, String, Object> data = TreeBasedTable.create();
    // get existing or create new DeviceCache
    DeviceCache deviceCache = this.deviceCacheMap.get(edgeId);
    if (deviceCache == null) {
        deviceCache = new DeviceCache();
        this.deviceCacheMap.put(edgeId, deviceCache);
    }
    // Sort incoming data by timestamp
    TreeMap<Long, JsonObject> sortedData = new TreeMap<Long, JsonObject>();
    for (Entry<String, JsonElement> entry : jData.entrySet()) {
        try {
            Long timestamp = Long.valueOf(entry.getKey());
            JsonObject jChannels;
            jChannels = JsonUtils.getAsJsonObject(entry.getValue());
            sortedData.put(timestamp, jChannels);
        } catch (OpenemsException e) {
            log.error("Data error: " + e.getMessage());
        }
    }
    // order)
    for (Entry<Long, JsonObject> dataEntry : sortedData.entrySet()) {
        Long timestamp = dataEntry.getKey();
        JsonObject jChannels = dataEntry.getValue();
        if (jChannels.entrySet().size() == 0) {
            // no channel values available. abort.
            continue;
        }
        // Check if cache is valid (it is not elder than 5 minutes compared to this
        // timestamp)
        long cacheTimestamp = deviceCache.getTimestamp();
        if (timestamp < cacheTimestamp) {
        // incoming data is older than cache -> do not apply cache
        } else {
            // incoming data is more recent than cache
            // update cache timestamp
            deviceCache.setTimestamp(timestamp);
            if (timestamp < cacheTimestamp + 5 * 60 * 1000) {
                // add cache data to write data
                for (Entry<String, Object> cacheEntry : deviceCache.getChannelCacheEntries()) {
                    String channel = cacheEntry.getKey();
                    Object value = cacheEntry.getValue();
                    data.put(timestamp, channel, value);
                }
            } else {
                // clear cache
                if (cacheTimestamp != 0l) {
                    log.info("Edge [" + edge.getName() + "]: invalidate cache for influxId [" + influxId + "]. This timestamp [" + timestamp + "]. Cache timestamp [" + cacheTimestamp + "]");
                }
                deviceCache.clear();
            }
            // add incoming data to cache (this replaces already existing cache values)
            for (Entry<String, JsonElement> channelEntry : jChannels.entrySet()) {
                String channel = channelEntry.getKey();
                Optional<Object> valueOpt = InfluxdbUtils.parseValue(channel, channelEntry.getValue());
                if (valueOpt.isPresent()) {
                    Object value = valueOpt.get();
                    deviceCache.putToChannelCache(channel, value);
                }
            }
        }
        // add incoming data to write data
        for (Entry<String, JsonElement> channelEntry : jChannels.entrySet()) {
            String channel = channelEntry.getKey();
            Optional<Object> valueOpt = InfluxdbUtils.parseValue(channel, channelEntry.getValue());
            if (valueOpt.isPresent()) {
                Object value = valueOpt.get();
                data.put(timestamp, channel, value);
            }
        }
    }
    // Write data to default location
    writeData(influxId, data);
    // Hook to continue writing data to old Mini monitoring
    if (edge.getProducttype().equals("MiniES 3-3")) {
        writeDataToOldMiniMonitoring(edge, influxId, data);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) TreeMap(java.util.TreeMap) Point(org.influxdb.dto.Point) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) Edge(io.openems.backend.metadata.api.Edge)

Example 22 with OpenemsException

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

Example 23 with OpenemsException

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

the class UiWebsocketServer method handleEdgeReply.

public void handleEdgeReply(int edgeId, JsonObject jMessage) throws OpenemsException {
    JsonObject jMessageId = JsonUtils.getAsJsonObject(jMessage, "messageId");
    String backendId = JsonUtils.getAsString(jMessageId, "backend");
    WebSocket websocket = this.websocketsMap.get(UUID.fromString(backendId));
    if (websocket != null) {
        JsonObject j = DefaultMessages.prepareMessageForForwardToUi(jMessage);
        WebSocketUtils.send(websocket, j);
        return;
    }
    throw new OpenemsException("No websocket found for UUID [" + backendId + "]");
}
Also used : JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) WebSocket(org.java_websocket.WebSocket)

Example 24 with OpenemsException

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

the class ChannelExport method main.

public static void main(String[] args) throws OpenemsException {
    String openemsPath = "C:\\Users\\matthias.rossmann\\Dev\\git\\openems-neu\\edge\\src";
    Collection<ThingDoc> deviceNatures;
    HashMap<Path, FileWriter> files = new HashMap<>();
    try {
        deviceNatures = ClassRepository.getInstance().getAvailableDeviceNatures();
        FileWriter devices = new FileWriter(Paths.get(openemsPath, "\\io\\openems\\impl\\device\\Readme.md").toFile());
        devices.write("# List of implemented Devices.\r\n\r\n");
        for (ThingDoc thingDoc : deviceNatures) {
            try {
                System.out.println(thingDoc.getClazz().getName());
                if (thingDoc.getClazz().equals(AsymmetricSymmetricCombinationEssNature.class) || thingDoc.getClazz().equals(EssClusterNature.class) || thingDoc.getClazz().isInterface() || Modifier.isAbstract(thingDoc.getClazz().getModifiers())) {
                    continue;
                }
                Path p = Paths.get(openemsPath, thingDoc.getClazz().getName().replaceAll("[^\\.]*$", "").replace(".", "/"), "Readme.md");
                FileWriter fw;
                if (files.containsKey(p)) {
                    fw = files.get(p);
                } else {
                    fw = new FileWriter(p.toFile());
                    files.put(p, fw);
                    fw.write("");
                }
                fw.append("# " + thingDoc.getTitle() + "\r\n" + thingDoc.getText() + "\r\n\r\nFollowing Values are implemented:\r\n\r\n" + "|ChannelName|Unit|\r\n" + "|---|---|\r\n");
                devices.append("* [" + thingDoc.getTitle() + "](" + Paths.get(thingDoc.getClazz().getName().replaceAll("io.openems.impl.device.", "").replaceAll("[^\\.]*$", "").replace(".", "/"), "Readme.md").toString().replace("\\", "/") + ")\r\n");
                Thing thing = thingDoc.getClazz().getConstructor(String.class, Device.class).newInstance("", null);
                if (thing instanceof ModbusDeviceNature) {
                    ((ModbusDeviceNature) thing).init();
                }
                List<ChannelDoc> channelDocs = new LinkedList<>(thingDoc.getChannelDocs());
                Collections.sort(channelDocs, new Comparator<ChannelDoc>() {

                    @Override
                    public int compare(ChannelDoc arg0, ChannelDoc arg1) {
                        return arg0.getName().compareTo(arg1.getName());
                    }
                });
                for (ChannelDoc channelDoc : channelDocs) {
                    Member member = channelDoc.getMember();
                    try {
                        List<Channel> channels = new ArrayList<>();
                        if (member instanceof Method) {
                            if (((Method) member).getReturnType().isArray()) {
                                Channel[] ch = (Channel[]) ((Method) member).invoke(thing);
                                for (Channel c : ch) {
                                    channels.add(c);
                                }
                            } else {
                                // It's a Method with ReturnType Channel
                                channels.add((Channel) ((Method) member).invoke(thing));
                            }
                        } else if (member instanceof Field) {
                            // It's a Field with Type Channel
                            channels.add((Channel) ((Field) member).get(thing));
                        } else {
                            continue;
                        }
                        if (channels.isEmpty()) {
                            System.out.println("Channel is returning null! Thing [" + thing.id() + "], Member [" + member.getName() + "]");
                            continue;
                        }
                        for (Channel channel : channels) {
                            if (channel != null) {
                                StringBuilder unit = new StringBuilder();
                                if (channel instanceof ReadChannel) {
                                    ReadChannel rchannel = ((ReadChannel) channel);
                                    unit.append(rchannel.unitOptional());
                                    rchannel.getLabels().forEach((key, value) -> {
                                        unit.append(key + ": " + value + "<br/>");
                                    });
                                }
                                fw.append("|" + channel.id() + "|" + unit + "|\r\n");
                            }
                        }
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        System.out.println("Unable to add Channel. Member [" + member.getName() + "]");
                    }
                }
            } catch (NoSuchMethodException e) {
            }
        }
        for (FileWriter fw : files.values()) {
            fw.close();
        }
        devices.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HashMap(java.util.HashMap) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) ReadChannel(io.openems.api.channel.ReadChannel) Field(java.lang.reflect.Field) EssClusterNature(io.openems.impl.device.system.esscluster.EssClusterNature) Member(java.lang.reflect.Member) Thing(io.openems.api.thing.Thing) ThingDoc(io.openems.api.doc.ThingDoc) Path(java.nio.file.Path) Device(io.openems.api.device.Device) ReadChannel(io.openems.api.channel.ReadChannel) Channel(io.openems.api.channel.Channel) Method(java.lang.reflect.Method) ChannelDoc(io.openems.api.doc.ChannelDoc) LinkedList(java.util.LinkedList) InvocationTargetException(java.lang.reflect.InvocationTargetException) OpenemsException(io.openems.common.exceptions.OpenemsException) InvocationTargetException(java.lang.reflect.InvocationTargetException) AsymmetricSymmetricCombinationEssNature(io.openems.impl.device.system.asymmetricsymmetriccombinationess.AsymmetricSymmetricCombinationEssNature) ModbusDeviceNature(io.openems.impl.protocol.modbus.ModbusDeviceNature)

Example 25 with OpenemsException

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

the class FaultsAndWarningsTranspiler method getJson.

private static JsonObject getJson() throws ReflectionException, OpenemsException {
    JsonObject j = new JsonObject();
    for (Class<ThingStateEnum> clazz : getEnums()) {
        ThingStateInfo annotation = clazz.getAnnotation(ThingStateInfo.class);
        if (annotation == null) {
            System.err.println("@ThingStateInfo is missing for Enum [" + clazz.getName() + "]");
            continue;
        }
        // Find existing Thing definition or create new one
        for (Class<?> thingClazz : annotation.reference()) {
            String thingClassName = thingClazz.getName();
            JsonObject jThing = JsonUtils.getAsOptionalJsonObject(j, thingClassName).orElse(new JsonObject());
            // Parse enum constants
            ThingStateEnum[] enoms = clazz.getEnumConstants();
            JsonObject jState = new JsonObject();
            for (ThingStateEnum enom : enoms) {
                String name = splitCamelCase(enom.toString());
                jState.addProperty(String.valueOf(enom.getValue()), name);
            }
            // Is it Fault or Warning?
            if (FaultEnum.class.isAssignableFrom(clazz)) {
                jThing.add("faults", jState);
            } else if (WarningEnum.class.isAssignableFrom(clazz)) {
                jThing.add("warnings", jState);
            } else {
                throw new OpenemsException("Neither Fault nor Warning in Enum [" + clazz.getName() + "]");
            }
            j.add(thingClassName, jThing);
        }
    }
    return j;
}
Also used : ThingStateEnum(io.openems.api.channel.thingstate.ThingStateEnum) ThingStateInfo(io.openems.common.types.ThingStateInfo) JsonObject(com.google.gson.JsonObject) WarningEnum(io.openems.api.channel.thingstate.WarningEnum) OpenemsException(io.openems.common.exceptions.OpenemsException)

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