use of io.openems.core.ThingRepository in project openems by OpenEMS.
the class WebsocketLogAppender method append.
@Override
protected void append(ILoggingEvent event) {
long timestamp = event.getTimeStamp();
String level = event.getLevel().toString();
String source = event.getLoggerName();
String message = event.getFormattedMessage();
ThingRepository thingRepository = ThingRepository.getInstance();
for (Scheduler scheduler : thingRepository.getSchedulers()) {
for (Controller controller : scheduler.getControllers()) {
if (controller instanceof WebsocketApiController) {
WebsocketApiController websocketApiController = (WebsocketApiController) controller;
websocketApiController.sendLog(timestamp, level, source, message);
}
}
}
// send to fenecon persistence
ThingRepository.getInstance().getPersistences().forEach((persistence) -> {
if (persistence instanceof FeneconPersistence) {
FeneconPersistence p = (FeneconPersistence) persistence;
p.sendLog(timestamp, level, source, message);
}
});
}
use of io.openems.core.ThingRepository in project openems by OpenEMS.
the class ConfigUtils method getAsJsonElement.
/**
* Converts an object to a JsonElement
*
* @param value
* @return
* @throws NotImplementedException
*/
public static JsonElement getAsJsonElement(Object value, ConfigFormat format, Role role) throws NotImplementedException {
// null
if (value == null) {
return null;
}
// optional
if (value instanceof Optional<?>) {
if (!((Optional<?>) value).isPresent()) {
return null;
} else {
value = ((Optional<?>) value).get();
}
}
try {
/*
* test for simple types
*/
return JsonUtils.getAsJsonElement(value);
} catch (NotImplementedException e) {
;
}
if (value instanceof Thing) {
/*
* type Thing
*/
Thing thing = (Thing) value;
JsonObject j = new JsonObject();
if (format == ConfigFormat.OPENEMS_UI || !thing.id().startsWith("_")) {
// ignore generated id names starting with "_"
j.addProperty("id", thing.id());
j.addProperty("alias", thing.getAlias());
}
// for file-format class is not needed for DeviceNatures
j.addProperty("class", thing.getClass().getCanonicalName());
ThingRepository thingRepository = ThingRepository.getInstance();
for (ConfigChannel<?> channel : thingRepository.getConfigChannels(thing)) {
if (channel.isReadAllowed(role)) {
// check read permissions
JsonElement jChannel = null;
jChannel = ConfigUtils.getAsJsonElement(channel, format, role);
if (jChannel != null) {
j.add(channel.id(), jChannel);
}
}
}
// for Bridge: add 'devices' array of thingIds
if (value instanceof Bridge) {
Bridge bridge = (Bridge) value;
JsonArray jDevices = new JsonArray();
for (Device device : bridge.getDevices()) {
jDevices.add(device.id());
}
j.add("devices", jDevices);
}
return j;
} else if (value instanceof ConfigChannel<?>) {
/*
* type ConfigChannel
*/
ConfigChannel<?> channel = (ConfigChannel<?>) value;
if (!channel.valueOptional().isPresent()) {
// no value set
return null;
} else if (format == ConfigFormat.FILE && channel.getDefaultValue().equals(channel.valueOptional())) {
// default value not changed
return null;
} else {
// recursive call
return ConfigUtils.getAsJsonElement(channel.valueOptional().get(), format, role);
}
} else if (value instanceof ThingMap) {
/*
* ThingMap (we need only id)
*/
return new JsonPrimitive(((ThingMap) value).id());
} else if (value instanceof List<?>) {
/*
* List
*/
JsonArray jArray = new JsonArray();
for (Object v : (List<?>) value) {
jArray.add(ConfigUtils.getAsJsonElement(v, format, role));
}
return jArray;
} else if (value instanceof Set<?>) {
/*
* Set
*/
JsonArray jArray = new JsonArray();
for (Object v : (Set<?>) value) {
jArray.add(ConfigUtils.getAsJsonElement(v, format, role));
}
return jArray;
}
throw new NotImplementedException(//
"Converter for [" + value + "]" + " of type [" + value.getClass().getSimpleName() + //
"]" + " to JSON is not implemented.");
}
use of io.openems.core.ThingRepository in project openems by OpenEMS.
the class ConfigUtils method getThingFromConfig.
private static Thing getThingFromConfig(Class<? extends Thing> type, JsonElement j, Object... objects) throws OpenemsException {
String thingId = JsonUtils.getAsString(j, "id");
ThingRepository thingRepository = ThingRepository.getInstance();
Optional<Thing> existingThing = thingRepository.getThingById(thingId);
Thing thing;
if (existingThing.isPresent()) {
// reuse existing Thing
thing = existingThing.get();
} else {
// Thing is not existing. Create a new instance
Object[] args = new Object[objects.length + 1];
args[0] = thingId;
for (int i = 1; i < objects.length + 1; i++) {
args[i] = objects[i - 1];
}
thing = InjectionUtils.getThingInstance(type, args);
log.debug("Add Thing[" + thing.id() + "], Implementation[" + thing.getClass().getSimpleName() + "]");
thingRepository.addThing(thing);
}
// Recursive call to inject config parameters for the newly created Thing
injectConfigChannels(thingRepository.getConfigChannels(thing), j.getAsJsonObject());
// thing.init();
return thing;
}
use of io.openems.core.ThingRepository in project openems by OpenEMS.
the class InjectionUtils method getThingMapsFromConfig.
public static Object getThingMapsFromConfig(ConfigChannel<?> channel, JsonElement j) throws ReflectionException {
/*
* Get "Field" in Channels parent class
*/
Field field;
try {
field = channel.parent().getClass().getField(channel.id());
} catch (NoSuchFieldException | SecurityException e) {
throw new ReflectionException("Field for ConfigChannel [" + channel.address() + "] is not named [" + channel.id() + "] in [" + channel.getClass().getSimpleName() + "]");
}
/*
* Get expected Object Type (List, Set, simple Object)
*/
Type expectedObjectType = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
if (expectedObjectType instanceof ParameterizedType) {
expectedObjectType = ((ParameterizedType) expectedObjectType).getRawType();
}
Class<?> expectedObjectClass = (Class<?>) expectedObjectType;
/*
* Get the ThingMap class
*/
Class<?> thingMapClass = channel.type().get();
/*
* Get the referenced Thing class
*/
IsThingMap isThingMapAnnotation = thingMapClass.getAnnotation(IsThingMap.class);
Class<? extends Thing> thingClass = isThingMapAnnotation.type();
/*
* Prepare filter for matching Things
* - Empty filter: accept nothing
* - Asterisk: accept everything
* - Otherwise: accept only exact string matches on the thing id
*/
Set<String> filter = new HashSet<>();
if (j.isJsonPrimitive()) {
String id = j.getAsJsonPrimitive().getAsString();
filter.add(id);
} else if (j.isJsonArray()) {
j.getAsJsonArray().forEach(id -> filter.add(id.getAsString()));
}
/*
* Create ThingMap instance(s) for each matching Thing
*/
ThingRepository thingRepository = ThingRepository.getInstance();
Set<Thing> matchingThings = thingRepository.getThingsAssignableByClass(thingClass);
Set<ThingMap> thingMaps = new HashSet<>();
for (Thing thing : matchingThings) {
if (filter.contains(thing.id()) || filter.contains("*")) {
ThingMap thingMap = (ThingMap) InjectionUtils.getInstance(thingMapClass, thing);
thingMaps.add(thingMap);
}
}
/*
* Prepare return
*/
if (thingMaps.isEmpty() && !filter.isEmpty()) {
throw new ReflectionException("No matching ThingMap found for ConfigChannel [" + channel.address() + "]");
}
if (Collection.class.isAssignableFrom(expectedObjectClass)) {
if (Set.class.isAssignableFrom(expectedObjectClass)) {
return thingMaps;
} else if (List.class.isAssignableFrom(expectedObjectClass)) {
return new ArrayList<>(thingMaps);
} else {
throw new ReflectionException("Only List and Set ConfigChannels are currently implemented, not [" + expectedObjectClass + "]. ConfigChannel [" + channel.address() + "]");
}
} else {
// No collection
if (thingMaps.size() > 1) {
throw new ReflectionException("Field for ConfigChannel [" + channel.address() + "] is no collection, but more than one ThingMaps [" + thingMaps + "] is fitting for [" + channel.id() + "] in [" + channel.getClass().getSimpleName() + "]");
} else {
return thingMaps.iterator().next();
}
}
}
use of io.openems.core.ThingRepository in project openems by OpenEMS.
the class ModbusTcpApiController method updateChannelMapping.
protected void updateChannelMapping(Optional<JsonObject> jMappingOpt) {
processImage.clearMapping();
ThingRepository thingRepository = ThingRepository.getInstance();
if (jMappingOpt.isPresent()) {
JsonObject jMapping = jMappingOpt.get();
for (Entry<String, JsonElement> entry : jMapping.entrySet()) {
try {
int ref = Integer.parseInt(entry.getKey());
ChannelAddress channelAddress = ChannelAddress.fromString(JsonUtils.getAsString(entry.getValue()));
Optional<ChannelDoc> channelDocOpt = thingRepository.getChannelDoc(channelAddress);
if (channelDocOpt.isPresent()) {
processImage.addMapping(ref, channelAddress, channelDocOpt.get());
} else {
Optional<Channel> channelOpt = thingRepository.getChannel(channelAddress);
if (channelOpt.isPresent()) {
throw new OpenemsException("ChannelDoc for channel [" + channelAddress + "] is not available.");
} else {
throw new OpenemsException("Channel [" + channelAddress + "] does not exist.");
}
}
} catch (Exception e) {
log.error("Unable to add channel mapping: " + e.getMessage());
}
}
}
}
Aggregations