Search in sources :

Example 1 with ThingRepository

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);
        }
    });
}
Also used : ThingRepository(io.openems.core.ThingRepository) WebsocketApiController(io.openems.impl.controller.api.websocket.WebsocketApiController) FeneconPersistence(io.openems.impl.persistence.fenecon.FeneconPersistence) Scheduler(io.openems.api.scheduler.Scheduler) Controller(io.openems.api.controller.Controller) WebsocketApiController(io.openems.impl.controller.api.websocket.WebsocketApiController)

Example 2 with ThingRepository

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.");
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Optional(java.util.Optional) JsonPrimitive(com.google.gson.JsonPrimitive) Device(io.openems.api.device.Device) ConfigChannel(io.openems.api.channel.ConfigChannel) NotImplementedException(io.openems.common.exceptions.NotImplementedException) JsonObject(com.google.gson.JsonObject) ThingRepository(io.openems.core.ThingRepository) JsonArray(com.google.gson.JsonArray) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) ThingMap(io.openems.api.controller.ThingMap) Thing(io.openems.api.thing.Thing) Bridge(io.openems.api.bridge.Bridge)

Example 3 with ThingRepository

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;
}
Also used : ThingRepository(io.openems.core.ThingRepository) JsonObject(com.google.gson.JsonObject) Thing(io.openems.api.thing.Thing)

Example 4 with ThingRepository

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();
        }
    }
}
Also used : Arrays(java.util.Arrays) ReflectionException(io.openems.api.exception.ReflectionException) Collection(java.util.Collection) ConfigException(io.openems.api.exception.ConfigException) Set(java.util.Set) Thing(io.openems.api.thing.Thing) ConfigChannel(io.openems.api.channel.ConfigChannel) Field(java.lang.reflect.Field) Constructor(java.lang.reflect.Constructor) InvocationTargetException(java.lang.reflect.InvocationTargetException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) JsonElement(com.google.gson.JsonElement) List(java.util.List) JsonArray(com.google.gson.JsonArray) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) IsThingMap(io.openems.api.controller.IsThingMap) ThingRepository(io.openems.core.ThingRepository) DeviceNature(io.openems.api.device.nature.DeviceNature) ThingMap(io.openems.api.controller.ThingMap) ReflectionException(io.openems.api.exception.ReflectionException) ParameterizedType(java.lang.reflect.ParameterizedType) ThingRepository(io.openems.core.ThingRepository) Field(java.lang.reflect.Field) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ArrayList(java.util.ArrayList) List(java.util.List) IsThingMap(io.openems.api.controller.IsThingMap) ThingMap(io.openems.api.controller.ThingMap) IsThingMap(io.openems.api.controller.IsThingMap) Thing(io.openems.api.thing.Thing) HashSet(java.util.HashSet)

Example 5 with ThingRepository

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());
            }
        }
    }
}
Also used : ConfigChannel(io.openems.api.channel.ConfigChannel) Channel(io.openems.api.channel.Channel) JsonObject(com.google.gson.JsonObject) ChannelAddress(io.openems.common.types.ChannelAddress) OpenemsException(io.openems.common.exceptions.OpenemsException) ChannelDoc(io.openems.api.doc.ChannelDoc) OpenemsException(io.openems.common.exceptions.OpenemsException) ModbusException(com.ghgande.j2mod.modbus.ModbusException) ThingRepository(io.openems.core.ThingRepository) JsonElement(com.google.gson.JsonElement)

Aggregations

ThingRepository (io.openems.core.ThingRepository)5 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)3 ConfigChannel (io.openems.api.channel.ConfigChannel)3 Thing (io.openems.api.thing.Thing)3 JsonArray (com.google.gson.JsonArray)2 ThingMap (io.openems.api.controller.ThingMap)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 ModbusException (com.ghgande.j2mod.modbus.ModbusException)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 Bridge (io.openems.api.bridge.Bridge)1 Channel (io.openems.api.channel.Channel)1 Controller (io.openems.api.controller.Controller)1 IsThingMap (io.openems.api.controller.IsThingMap)1 Device (io.openems.api.device.Device)1 DeviceNature (io.openems.api.device.nature.DeviceNature)1 ChannelDoc (io.openems.api.doc.ChannelDoc)1 ConfigException (io.openems.api.exception.ConfigException)1 ReflectionException (io.openems.api.exception.ReflectionException)1