Search in sources :

Example 1 with Bridge

use of io.openems.api.bridge.Bridge in project openems by OpenEMS.

the class Config method getBridgesJson.

public JsonArray getBridgesJson(ConfigFormat format, Role role) throws NotImplementedException {
    JsonArray jBridges = new JsonArray();
    for (Bridge bridge : thingRepository.getBridges()) {
        JsonObject jBridge = (JsonObject) ConfigUtils.getAsJsonElement(bridge, format, role);
        /*
			 * Device
			 */
        JsonArray jDevices = new JsonArray();
        for (Device device : bridge.getDevices()) {
            JsonObject jDevice = (JsonObject) ConfigUtils.getAsJsonElement(device, format, role);
            jDevices.add(jDevice);
        }
        jBridge.add("devices", jDevices);
        jBridges.add(jBridge);
    }
    return jBridges;
}
Also used : JsonArray(com.google.gson.JsonArray) Device(io.openems.api.device.Device) JsonObject(com.google.gson.JsonObject) Bridge(io.openems.api.bridge.Bridge)

Example 2 with Bridge

use of io.openems.api.bridge.Bridge in project openems by OpenEMS.

the class ThingRepository method removeThing.

/**
 * Remove a Thing from the Repository.
 *
 * @param thing
 */
public synchronized void removeThing(Thing thing) {
    // Remove from thingIds
    thingIds.remove(thing.id());
    // Remove from thingClasses
    thingClasses.remove(thing.getClass(), thing);
    // Remove from bridges
    if (thing instanceof Bridge) {
        bridges.remove(thing);
    }
    // Remove from schedulers
    if (thing instanceof Scheduler) {
        schedulers.remove(thing);
    }
    // Remove from persistences
    if (thing instanceof Persistence) {
        persistences.remove(thing);
    }
    // Remove from queryablePersistences
    if (thing instanceof QueryablePersistence) {
        queryablePersistences.remove(thing);
    }
    // Remove from deviceNatures
    if (thing instanceof DeviceNature) {
        deviceNatures.remove(thing);
    }
    // Remove controller
    if (thing instanceof Controller) {
        Controller controller = (Controller) thing;
        for (Scheduler scheduler : getSchedulers()) {
            scheduler.removeController(controller);
        }
    }
    // Remove device
    if (thing instanceof Device) {
        for (Bridge bridge : bridges) {
            bridge.removeDevice((Device) thing);
        }
    }
    // Remove Listener
    thing.removeListener(this);
    for (ThingsChangedListener listener : thingListeners) {
        listener.thingChanged(thing, Action.REMOVE);
    }
}
Also used : QueryablePersistence(io.openems.api.persistence.QueryablePersistence) Persistence(io.openems.api.persistence.Persistence) QueryablePersistence(io.openems.api.persistence.QueryablePersistence) Scheduler(io.openems.api.scheduler.Scheduler) Device(io.openems.api.device.Device) DeviceNature(io.openems.api.device.nature.DeviceNature) Controller(io.openems.api.controller.Controller) Bridge(io.openems.api.bridge.Bridge)

Example 3 with Bridge

use of io.openems.api.bridge.Bridge 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 4 with Bridge

use of io.openems.api.bridge.Bridge in project openems by OpenEMS.

the class Config method parseJsonConfig.

public synchronized void parseJsonConfig(JsonObject jConfig) throws OpenemsException {
    /*
		 * read Users
		 */
    if (jConfig.has("users")) {
        JsonObject jUsers = JsonUtils.getAsJsonObject(jConfig, "users");
        for (Entry<String, JsonElement> jUsersElement : jUsers.entrySet()) {
            JsonObject jUser = JsonUtils.getAsJsonObject(jUsersElement.getValue());
            String username = jUsersElement.getKey();
            String passwordBase64 = JsonUtils.getAsString(jUser, "password");
            String saltBase64 = JsonUtils.getAsString(jUser, "salt");
            try {
                User.getUserByName(username).initialize(passwordBase64, saltBase64);
            } catch (OpenemsException e) {
                log.error("Error parsing config: " + e.getMessage());
            }
        }
    }
    // important! no more setting of users allowed!
    User.initializeFinished();
    /*
		 * read each Bridge in "things" array
		 */
    JsonArray jThings = JsonUtils.getAsJsonArray(jConfig, "things");
    for (JsonElement jBridgeElement : jThings) {
        JsonObject jBridge = JsonUtils.getAsJsonObject(jBridgeElement);
        String bridgeClass = JsonUtils.getAsString(jBridge, "class");
        Bridge bridge = (Bridge) InjectionUtils.getThingInstance(bridgeClass);
        thingRepository.addThing(bridge);
        log.info("Add Bridge[" + bridge.id() + "], Implementation[" + bridge.getClass().getSimpleName() + "]");
        ConfigUtils.injectConfigChannels(thingRepository.getConfigChannels(bridge), jBridge);
        /*
			 * read each Device in "things" array
			 */
        List<Device> devices = new ArrayList<>();
        JsonArray jDevices = JsonUtils.getAsJsonArray(jBridge, "devices");
        for (JsonElement jDeviceElement : jDevices) {
            JsonObject jDevice = JsonUtils.getAsJsonObject(jDeviceElement);
            Device device = thingRepository.createDevice(jDevice, bridge);
            devices.add(device);
            bridge.addDevice(device);
        }
    }
    /*
		 * Init bridge
		 */
    for (Bridge b : thingRepository.getBridges()) {
        for (Device d : b.getDevices()) {
            d.init();
        }
        b.init();
    }
    for (BridgeInitializedEventListener listener : bridgeInitEventListeners) {
        listener.onBridgeInitialized();
    }
    /*
		 * read Scheduler
		 */
    if (jConfig.has("scheduler")) {
        JsonObject jScheduler = JsonUtils.getAsJsonObject(jConfig, "scheduler");
        String schedulerClass = JsonUtils.getAsString(jScheduler, "class");
        Scheduler scheduler = (Scheduler) InjectionUtils.getThingInstance(schedulerClass);
        thingRepository.addThing(scheduler);
        log.debug("Add Scheduler[" + scheduler.id() + "], Implementation[" + scheduler.getClass().getSimpleName() + "]");
        ConfigUtils.injectConfigChannels(thingRepository.getConfigChannels(scheduler), jScheduler);
        /*
			 * read each Controller in "controllers" array
			 */
        JsonArray jControllers = JsonUtils.getAsJsonArray(jScheduler, "controllers");
        for (JsonElement jControllerElement : jControllers) {
            JsonObject jController = JsonUtils.getAsJsonObject(jControllerElement);
            Controller controller = thingRepository.createController(jController);
            scheduler.addController(controller);
            controller.init();
        }
        scheduler.init();
    }
    for (SchedulerInitializedEventListener listener : schedulerInitEventListeners) {
        listener.onSchedulerInitialized();
    }
    /*
		 * read Persistence
		 */
    if (jConfig.has("persistence")) {
        JsonArray jPersistences = JsonUtils.getAsJsonArray(jConfig, "persistence");
        for (JsonElement jPersistenceElement : jPersistences) {
            JsonObject jPersistence = JsonUtils.getAsJsonObject(jPersistenceElement);
            String persistenceClass = JsonUtils.getAsString(jPersistence, "class");
            Persistence persistence = (Persistence) InjectionUtils.getThingInstance(persistenceClass);
            thingRepository.addThing(persistence);
            log.info("Add Persistence[" + persistence.id() + "], Implementation[" + persistence.getClass().getSimpleName() + "]");
            ConfigUtils.injectConfigChannels(thingRepository.getConfigChannels(persistence), jPersistence);
            persistence.init();
        }
    }
    /*
		 * Configuration is finished -> apply again channel annotation to all of them because many channels are only
		 * defined during init()
		 */
    thingRepository.getThings().forEach(thing -> {
        thingRepository.applyChannelAnnotation(thing);
    });
    /*
		 * Start all worker threads
		 */
    thingRepository.getThings().forEach(thing -> {
        // TODO use executor
        if (thing instanceof Thread) {
            ((Thread) thing).start();
        }
    });
    /*
		 * Register myself as onChangeListener on all ConfigChannels
		 */
    for (ConfigChannel<?> channel : thingRepository.getConfigChannels()) {
        channel.addChangeListener(this);
    }
    /*
		 * After 10 seconds: build the ClassRepository cache to speed up future calls
		 * (this speeds up the first opening of the UI, as the cache does not need to be built)
		 */
    Executors.newScheduledThreadPool(1).schedule(() -> {
        try {
            ClassRepository.getInstance().getAvailableThings();
        } catch (ReflectionException e) {
        /* ignore */
        }
    }, 10, TimeUnit.SECONDS);
}
Also used : ReflectionException(io.openems.api.exception.ReflectionException) Device(io.openems.api.device.Device) Scheduler(io.openems.api.scheduler.Scheduler) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) Controller(io.openems.api.controller.Controller) JsonArray(com.google.gson.JsonArray) Persistence(io.openems.api.persistence.Persistence) JsonElement(com.google.gson.JsonElement) Bridge(io.openems.api.bridge.Bridge)

Example 5 with Bridge

use of io.openems.api.bridge.Bridge in project openems by OpenEMS.

the class ThingRepository method addThing.

/**
 * Add a Thing to the Repository and cache its Channels and other information for later usage.
 *
 * @param thing
 */
public synchronized void addThing(Thing thing) {
    if (thingIds.containsValue(thing)) {
        // Thing was already added
        return;
    }
    // Add to thingIds
    thingIds.forcePut(thing.id(), thing);
    // Add to thingClasses
    thingClasses.put(thing.getClass(), thing);
    // Add to bridges
    if (thing instanceof Bridge) {
        bridges.add((Bridge) thing);
    }
    // Add to schedulers
    if (thing instanceof Scheduler) {
        schedulers.add((Scheduler) thing);
    }
    // Add to persistences
    if (thing instanceof Persistence) {
        persistences.add((Persistence) thing);
    }
    // Add to queryablePersistences
    if (thing instanceof QueryablePersistence) {
        queryablePersistences.add((QueryablePersistence) thing);
    }
    // Add to device natures
    if (thing instanceof DeviceNature) {
        deviceNatures.add((DeviceNature) thing);
    }
    // Add Listener
    thing.addListener(this);
    // Apply channel annotation (this happens now and again after initializing the thing via init()
    this.applyChannelAnnotation(thing);
    // Add Channels thingConfigChannels
    ThingDoc thingDoc = classRepository.getThingDoc(thing.getClass());
    for (ChannelDoc channelDoc : thingDoc.getChannelDocs()) {
        Member member = channelDoc.getMember();
        try {
            List<Channel> channels = new ArrayList<>();
            java.util.function.Consumer<Channel> addToChannels = (c) -> {
                if (c == null) {
                // TODO this error is not handled properly
                // log.error(
                // "Channel is returning null! Thing [" + thing.id() + "], Member [" + member.getName() + "]");
                } else {
                    channels.add(c);
                }
            };
            if (member instanceof Method) {
                if (((Method) member).getReturnType().isArray()) {
                    Channel[] ch = (Channel[]) ((Method) member).invoke(thing);
                    for (Channel c : ch) {
                        addToChannels.accept(c);
                    }
                } else {
                    // It's a Method with ReturnType Channel
                    Channel c = (Channel) ((Method) member).invoke(thing);
                    addToChannels.accept(c);
                    if (c instanceof ThingStateChannels) {
                        ThingStateChannels tsc = (ThingStateChannels) c;
                        for (ThingStateChannel fc : tsc.getFaultChannels()) {
                            addToChannels.accept(fc);
                        }
                        for (ThingStateChannel wc : tsc.getWarningChannels()) {
                            addToChannels.accept(wc);
                        }
                    }
                }
            } else if (member instanceof Field) {
                // It's a Field with Type Channel
                Channel c = (Channel) ((Field) member).get(thing);
                addToChannels.accept(c);
            } else {
                continue;
            }
            if (channels.isEmpty()) {
                continue;
            }
            for (Channel channel : channels) {
                // Add Channel to thingChannels
                thingChannels.put(thing, channel.id(), channel);
                if (channel instanceof ConfigChannel) {
                    // Add Channel to configChannels
                    thingConfigChannels.put(thing, (ConfigChannel<?>) channel);
                }
            }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            log.warn("Unable to add Channel. Member [" + member.getName() + "]", e);
        }
    }
    for (ThingsChangedListener listener : thingListeners) {
        listener.thingChanged(thing, Action.ADD);
    }
}
Also used : ReadChannel(io.openems.api.channel.ReadChannel) JsonObject(com.google.gson.JsonObject) Controller(io.openems.api.controller.Controller) OpenemsException(io.openems.common.exceptions.OpenemsException) LoggerFactory(org.slf4j.LoggerFactory) WriteChannel(io.openems.api.channel.WriteChannel) HashBasedTable(com.google.common.collect.HashBasedTable) ConfigChannel(io.openems.api.channel.ConfigChannel) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) HashMultimap(com.google.common.collect.HashMultimap) Bridge(io.openems.api.bridge.Bridge) Map(java.util.Map) DeviceNature(io.openems.api.device.nature.DeviceNature) Scheduler(io.openems.api.scheduler.Scheduler) LinkedList(java.util.LinkedList) Method(java.lang.reflect.Method) BiMap(com.google.common.collect.BiMap) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Member(java.lang.reflect.Member) Collection(java.util.Collection) JsonUtils(io.openems.common.utils.JsonUtils) Set(java.util.Set) Thing(io.openems.api.thing.Thing) ThingChannelsUpdatedListener(io.openems.api.thing.ThingChannelsUpdatedListener) Field(java.lang.reflect.Field) QueryablePersistence(io.openems.api.persistence.QueryablePersistence) InvocationTargetException(java.lang.reflect.InvocationTargetException) Device(io.openems.api.device.Device) Action(io.openems.core.ThingsChangedListener.Action) List(java.util.List) HashBiMap(com.google.common.collect.HashBiMap) ThingStateChannels(io.openems.api.channel.thingstate.ThingStateChannels) InjectionUtils(io.openems.core.utilities.InjectionUtils) Entry(java.util.Map.Entry) ConfigUtils(io.openems.core.utilities.ConfigUtils) Optional(java.util.Optional) Persistence(io.openems.api.persistence.Persistence) ChannelAddress(io.openems.common.types.ChannelAddress) ChannelDoc(io.openems.api.doc.ChannelDoc) ThingDoc(io.openems.api.doc.ThingDoc) Collections(java.util.Collections) Table(com.google.common.collect.Table) ThingStateChannel(io.openems.api.channel.ThingStateChannel) Channel(io.openems.api.channel.Channel) Scheduler(io.openems.api.scheduler.Scheduler) ConfigChannel(io.openems.api.channel.ConfigChannel) ArrayList(java.util.ArrayList) ThingStateChannels(io.openems.api.channel.thingstate.ThingStateChannels) ThingStateChannel(io.openems.api.channel.ThingStateChannel) Field(java.lang.reflect.Field) QueryablePersistence(io.openems.api.persistence.QueryablePersistence) DeviceNature(io.openems.api.device.nature.DeviceNature) Member(java.lang.reflect.Member) ThingDoc(io.openems.api.doc.ThingDoc) ReadChannel(io.openems.api.channel.ReadChannel) WriteChannel(io.openems.api.channel.WriteChannel) ConfigChannel(io.openems.api.channel.ConfigChannel) ThingStateChannel(io.openems.api.channel.ThingStateChannel) Channel(io.openems.api.channel.Channel) Method(java.lang.reflect.Method) ChannelDoc(io.openems.api.doc.ChannelDoc) InvocationTargetException(java.lang.reflect.InvocationTargetException) QueryablePersistence(io.openems.api.persistence.QueryablePersistence) Persistence(io.openems.api.persistence.Persistence) Bridge(io.openems.api.bridge.Bridge)

Aggregations

Bridge (io.openems.api.bridge.Bridge)6 Device (io.openems.api.device.Device)5 JsonObject (com.google.gson.JsonObject)4 JsonArray (com.google.gson.JsonArray)3 Controller (io.openems.api.controller.Controller)3 Persistence (io.openems.api.persistence.Persistence)3 Scheduler (io.openems.api.scheduler.Scheduler)3 JsonElement (com.google.gson.JsonElement)2 ConfigChannel (io.openems.api.channel.ConfigChannel)2 DeviceNature (io.openems.api.device.nature.DeviceNature)2 QueryablePersistence (io.openems.api.persistence.QueryablePersistence)2 Thing (io.openems.api.thing.Thing)2 OpenemsException (io.openems.common.exceptions.OpenemsException)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 BiMap (com.google.common.collect.BiMap)1 HashBasedTable (com.google.common.collect.HashBasedTable)1 HashBiMap (com.google.common.collect.HashBiMap)1 HashMultimap (com.google.common.collect.HashMultimap)1 Table (com.google.common.collect.Table)1