use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class SupplyBusSwitchController method generateSupplybuses.
private List<Supplybus> generateSupplybuses() {
if (esss.valueOptional().isPresent() && supplyBusConfig.valueOptional().isPresent() && switchDelay.valueOptional().isPresent()) {
List<Supplybus> buses = new ArrayList<>();
for (JsonElement bus : supplyBusConfig.valueOptional().get()) {
try {
String name = JsonUtils.getAsString(bus, "bus");
String primaryEssName = JsonUtils.getAsString(bus, "primaryEss");
JsonElement supplybusOnIndicationElement = bus.getAsJsonObject().get("supplybusOnIndication");
JsonElement loads = bus.getAsJsonObject().get("loads");
Optional<Channel> supplybusOnIndication = Optional.empty();
if (supplybusOnIndicationElement != null) {
supplybusOnIndication = repo.getChannelByAddress(supplybusOnIndicationElement.getAsString());
}
List<WriteChannel<Long>> loadChannels = new ArrayList<>();
if (loads != null) {
for (JsonElement load : loads.getAsJsonArray()) {
Optional<Channel> loadChannel = repo.getChannelByAddress(load.getAsString());
if (loadChannel.isPresent() && loadChannel.get() instanceof WriteChannel<?>) {
@SuppressWarnings("unchecked") WriteChannel<Long> writeChannel = (WriteChannel<Long>) loadChannel.get();
loadChannels.add(writeChannel);
}
}
}
Ess primaryEss = getEss(primaryEssName);
HashMap<Ess, WriteChannel<Boolean>> switchEssMapping = new HashMap<>();
JsonArray switches = JsonUtils.getAsJsonArray(bus, "switches");
for (JsonElement e : switches) {
try {
String essName = JsonUtils.getAsString(e, "ess");
try {
Ess ess = getEss(essName);
String channelAddress = JsonUtils.getAsString(e, "switchAddress");
Optional<Channel> outputChannel = repo.getChannelByAddress(channelAddress);
if (ess != null) {
if (outputChannel.isPresent() && outputChannel.get() instanceof WriteChannel<?>) {
@SuppressWarnings("unchecked") WriteChannel<Boolean> channel = (WriteChannel<Boolean>) outputChannel.get();
channel.required();
switchEssMapping.put(ess, channel);
} else {
log.error(channelAddress + " not found!");
}
} else {
log.error(essName + "not found!");
}
} catch (InvalidValueException e1) {
log.error(essName + " is missing in the 'esss' config parameter", e1);
}
} catch (ReflectionException e2) {
log.error("can't find JsonElement 'ess' or 'switchAddress'!", e2);
}
}
WriteChannel<Long> supplybusOnIndicationChannel = null;
if (supplybusOnIndication.isPresent()) {
if (supplybusOnIndication.get() instanceof WriteChannel<?>) {
@SuppressWarnings("unchecked") WriteChannel<Long> writeChannel = (WriteChannel<Long>) supplybusOnIndication.get();
supplybusOnIndicationChannel = writeChannel;
}
}
Supplybus sb = new Supplybus(switchEssMapping, name, primaryEss, switchDelay.value(), supplybusOnIndicationChannel, loadChannels);
buses.add(sb);
} catch (ReflectionException e) {
log.error("can't find JsonElement 'bus' or 'switches' in config parameter 'supplyBuses'!", e);
} catch (InvalidValueException e3) {
log.error("primaryEss not found", e3);
} catch (OpenemsException e4) {
log.error(e4.getMessage());
}
}
return buses;
} else {
return null;
}
}
use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class ConfigChannel method setChannelDoc.
/**
* Sets values for this ConfigChannel using its annotation
*
* This method is called by reflection from {@link InjectionUtils.getThingInstance}
*
* @param parent
* @throws OpenemsException
*/
@Override
public void setChannelDoc(ChannelDoc channelDoc) throws OpenemsException {
super.setChannelDoc(channelDoc);
if (!this.isOptional.isPresent()) {
this.isOptional = Optional.of(channelDoc.isOptional());
}
if (!this.defaultValue.isPresent() && !channelDoc.getDefaultValue().isEmpty()) {
JsonElement jValue = null;
try {
jValue = (new JsonParser()).parse(channelDoc.getDefaultValue());
@SuppressWarnings("unchecked") T value = (T) JsonUtils.getAsType(type().get(), jValue);
this.defaultValue(value);
} catch (NotImplementedException | JsonSyntaxException e) {
throw new OpenemsException("Unable to set defaultValue [" + jValue + "] " + e.getMessage());
}
}
}
use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class EdgeWebsocketHandler method onMessage.
/**
* Handles a message from Websocket.
*
* @param jMessage
*/
public final void onMessage(JsonObject jMessage) {
if (!this.userOpt.isPresent()) {
log.error("No User! Aborting...");
return;
}
Role role = this.userOpt.get().getRole();
// get MessageId from message -> used for reply
Optional<JsonObject> jMessageIdOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "messageId");
if (jMessageIdOpt.isPresent()) {
JsonObject jMessageId = jMessageIdOpt.get();
/*
* Config
*/
Optional<JsonObject> jConfigOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "config");
if (jConfigOpt.isPresent()) {
this.config(role, jMessageId, apiWorkerOpt, jConfigOpt.get());
return;
}
/*
* Subscribe to currentData
*/
Optional<JsonObject> jCurrentDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "currentData");
if (jCurrentDataOpt.isPresent()) {
this.currentData(jMessageId, jCurrentDataOpt.get());
return;
}
/*
* Query historic data
*/
Optional<JsonObject> jhistoricDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "historicData");
if (jhistoricDataOpt.isPresent()) {
this.historicData(jMessageId, jhistoricDataOpt.get());
return;
}
/*
* Subscribe to log
*/
Optional<JsonObject> jLogOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "log");
if (jLogOpt.isPresent()) {
try {
this.log(role, jMessageId, jLogOpt.get());
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.UNABLE_TO_SUBSCRIBE_TO_LOG, e.getMessage());
}
}
/*
* Remote system control
*/
Optional<JsonObject> jSystemOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "system");
if (jSystemOpt.isPresent()) {
try {
this.system(jMessageId, jSystemOpt.get(), role);
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.UNABLE_TO_EXECUTE_SYSTEM_COMMAND, e.getMessage());
}
}
}
}
use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class EdgeWebsocketHandler method config.
/**
* Handle "config" messages
*
* @param jConfig
* @return
*/
private synchronized void config(Role role, JsonObject jMessageId, Optional<ApiWorker> apiWorkerOpt, JsonObject jConfig) {
Optional<String> modeOpt = JsonUtils.getAsOptionalString(jConfig, "mode");
switch(modeOpt.orElse("")) {
case "query":
/*
* Query current config
*/
try {
String language = JsonUtils.getAsString(jConfig, "language");
JsonObject jReplyConfig = Config.getInstance().getJson(ConfigFormat.OPENEMS_UI, role, language);
WebSocketUtils.send(this.websocket, DefaultMessages.configQueryReply(jMessageId, jReplyConfig));
return;
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.UNABLE_TO_READ_CURRENT_CONFIG, e.getMessage());
}
case "update":
/*
* Update thing/channel config
*/
Optional<String> thingIdOpt = JsonUtils.getAsOptionalString(jConfig, "thing");
Optional<String> channelIdOpt = JsonUtils.getAsOptionalString(jConfig, "channel");
try {
String thingId = thingIdOpt.get();
String channelId = channelIdOpt.get();
JsonElement jValue = JsonUtils.getSubElement(jConfig, "value");
Optional<Channel> channelOpt = ThingRepository.getInstance().getChannel(thingId, channelId);
if (channelOpt.isPresent()) {
Channel channel = channelOpt.get();
// check write permissions
channel.assertWriteAllowed(role);
if (channel instanceof ConfigChannel<?>) {
/*
* ConfigChannel
*/
ConfigChannel<?> configChannel = (ConfigChannel<?>) channel;
Object value = ConfigUtils.getConfigObject(configChannel, jValue);
configChannel.updateValue(value, true);
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_CHANNEL_UPDATE_SUCCESS, channel.address() + " => " + jValue);
} else if (channel instanceof WriteChannel<?>) {
/*
* WriteChannel
*/
WriteChannel<?> writeChannel = (WriteChannel<?>) channel;
if (!apiWorkerOpt.isPresent()) {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.BACKEND_NOT_ALLOWED, "set " + channel.address() + " => " + jValue);
} else {
ApiWorker apiWorker = apiWorkerOpt.get();
WriteObject writeObject = new WriteJsonObject(jValue).onFirstSuccess(() -> {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_CHANNEL_UPDATE_SUCCESS, "set " + channel.address() + " => " + jValue);
}).onFirstError((e) -> {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_CHANNEL_UPDATE_FAILED, "set " + channel.address() + " => " + jValue, e.getMessage());
}).onTimeout(() -> {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_CHANNEL_UPDATE_TIMEOUT, "set " + channel.address() + " => " + jValue);
});
apiWorker.addValue(writeChannel, writeObject);
}
}
} else {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.CHANNEL_NOT_FOUND, thingId + "/" + channelId);
}
} catch (NoSuchElementException | OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(this.websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_CHANNEL_UPDATE_FAILED, thingIdOpt.orElse("UNDEFINED") + "/" + channelIdOpt.orElse("UNDEFINED"), e.getMessage());
}
}
}
use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class EdgeWebsocketHandler method currentData.
// TODO implement creation of new things
// /*
// * Create new Thing
// */
// JsonObject jObject = JsonUtils.getAsJsonObject(jConfig, "object");
// String parentId = JsonUtils.getAsString(jConfig, "parent");
// String thingId = JsonUtils.getAsString(jObject, "id");
// if (thingId.startsWith("_")) {
// throw new ConfigException("IDs starting with underscore are reserved for internal use.");
// }
// if (thingRepository.getThingById(thingId).isPresent()) {
// throw new ConfigException("Thing Id is already existing.");
// }
// String clazzName = JsonUtils.getAsString(jObject, "class");
// Class<?> clazz = Class.forName(clazzName);
// if (Device.class.isAssignableFrom(clazz)) {
// // Device
// Thing parentThing = thingRepository.getThing(parentId);
// if (parentThing instanceof Bridge) {
// Bridge parentBridge = (Bridge) parentThing;
// Device device = thingRepository.createDevice(jObject);
// parentBridge.addDevice(device);
// Config.getInstance().writeConfigFile();
// Notification.send(NotificationType.SUCCESS, "Device [" + device.id() + "] wurde erstellt.");
// break;
// }
// }
// } else if (mode.equals("delete")) {
// TODO implement deletion of things
// /*
// * Delete a Thing
// */
// String thingId = JsonUtils.getAsString(jConfig, "thing");
// thingRepository.removeThing(thingId);
// Config.getInstance().writeConfigFile();
// Notification.send(NotificationType.SUCCESS, "Controller [" + thingId + "] wurde " + " gel�scht.");
// } else {
// throw new OpenemsException("Modus [" + mode + "] ist nicht implementiert.");
// }
// }
// TODO send new config after config update
// // Send new config
// JsonObject jMetadata = new JsonObject();
// jMetadata.add("config", Config.getInstance().getMetaConfigJson());
// JsonObject j = new JsonObject();
// j.add("metadata", jMetadata);
// WebSocketUtils.send(this.websocket, j);
// } catch (OpenemsException | ClassNotFoundException e) {
// Notification.send(NotificationType.ERROR, e.getMessage());
// }
// }
/**
* Handle current data subscriptions
* (try to keep synced with Backend.BrowserWebsocket)
*
* @param j
*/
private synchronized JsonObject currentData(JsonObject jMessageId, JsonObject jCurrentData) {
try {
String mode = JsonUtils.getAsString(jCurrentData, "mode");
if (mode.equals("subscribe")) {
/*
* Subscribe to channels
*/
if (!this.currentDataWorkerOpt.isPresent()) {
throw new OpenemsException("No CurrentDataWorker available");
}
JsonObject jSubscribeChannels = JsonUtils.getAsJsonObject(jCurrentData, "channels");
this.currentDataWorkerOpt.get().setChannels(jSubscribeChannels, jMessageId);
}
} catch (OpenemsException e) {
log.warn(e.getMessage());
}
return new JsonObject();
}
Aggregations