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);
}
}
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);
}
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 + "]");
}
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();
}
}
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;
}
Aggregations