Search in sources :

Example 1 with WriteChannel

use of io.openems.api.channel.WriteChannel in project openems by OpenEMS.

the class SupplyBusTest method setUpBeforeClass.

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    HashMap<Ess, WriteChannel<Boolean>> essSet = new HashMap<>();
    ess1 = new UnitTestSymmetricEssNature("ess0");
    essMap1 = new Ess(ess1);
    output1 = new UnitTestWriteChannel<>("output", "0");
    essSet.put(essMap1, output1);
    ess2 = new UnitTestSymmetricEssNature("ess1");
    essMap2 = new Ess(ess2);
    output2 = new UnitTestWriteChannel<>("output", "1");
    essSet.put(essMap2, output2);
    ess3 = new UnitTestSymmetricEssNature("ess2");
    essMap3 = new Ess(ess3);
    output3 = new UnitTestWriteChannel<>("output", "2");
    essSet.put(essMap3, output3);
    ess4 = new UnitTestSymmetricEssNature("ess3");
    essMap4 = new Ess(ess4);
    output4 = new UnitTestWriteChannel<>("output", "3");
    essSet.put(essMap4, output4);
    sbOnIndication = new UnitTestWriteChannel<>("custom", "sb1On");
    sb = new Supplybus(essSet, "sb1", essMap1, 1000L, sbOnIndication, new ArrayList<>());
}
Also used : Ess(io.openems.impl.controller.supplybusswitch.Ess) HashMap(java.util.HashMap) WriteChannel(io.openems.api.channel.WriteChannel) UnitTestWriteChannel(io.openems.test.utils.channel.UnitTestWriteChannel) ArrayList(java.util.ArrayList) UnitTestSymmetricEssNature(io.openems.test.utils.devicenatures.UnitTestSymmetricEssNature) Supplybus(io.openems.impl.controller.supplybusswitch.Supplybus) BeforeClass(org.junit.BeforeClass)

Example 2 with WriteChannel

use of io.openems.api.channel.WriteChannel 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;
    }
}
Also used : ReflectionException(io.openems.api.exception.ReflectionException) HashMap(java.util.HashMap) WriteChannel(io.openems.api.channel.WriteChannel) ConfigChannel(io.openems.api.channel.ConfigChannel) Channel(io.openems.api.channel.Channel) ArrayList(java.util.ArrayList) OpenemsException(io.openems.common.exceptions.OpenemsException) JsonArray(com.google.gson.JsonArray) InvalidValueException(io.openems.api.exception.InvalidValueException) JsonElement(com.google.gson.JsonElement) WriteChannel(io.openems.api.channel.WriteChannel)

Example 3 with WriteChannel

use of io.openems.api.channel.WriteChannel 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());
            }
    }
}
Also used : ApiWorker(io.openems.core.utilities.api.ApiWorker) ConfigChannel(io.openems.api.channel.ConfigChannel) WriteChannel(io.openems.api.channel.WriteChannel) ConfigChannel(io.openems.api.channel.ConfigChannel) Channel(io.openems.api.channel.Channel) JsonObject(com.google.gson.JsonObject) WriteJsonObject(io.openems.core.utilities.api.WriteJsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) JsonElement(com.google.gson.JsonElement) WriteChannel(io.openems.api.channel.WriteChannel) JsonObject(com.google.gson.JsonObject) WriteObject(io.openems.core.utilities.api.WriteObject) WriteJsonObject(io.openems.core.utilities.api.WriteJsonObject) WriteJsonObject(io.openems.core.utilities.api.WriteJsonObject) NoSuchElementException(java.util.NoSuchElementException) WriteObject(io.openems.core.utilities.api.WriteObject)

Example 4 with WriteChannel

use of io.openems.api.channel.WriteChannel in project openems by OpenEMS.

the class ChannelRegisterMap method setValue.

protected void setValue(MyRegister register, byte b1, byte b2) throws OpenemsException {
    int registerNo = register.getRegisterNo();
    this.setBuffer[registerNo * 2] = b1;
    this.setBuffer[registerNo * 2 + 1] = b2;
    // is the buffer full?
    for (int i = 0; i < this.setBuffer.length; i++) {
        if (this.setBuffer[i] == null) {
            // no, it is not full
            return;
        }
    }
    // yes, it is full -> parse value to Object
    byte[] value = new byte[this.setBuffer.length];
    boolean isPositive = true;
    for (int i = this.setBuffer.length - 1; i > 0; i -= 2) {
        if (((this.setBuffer[i - 1] >>> 8) & 1) != 0) {
            // test if the 'negative-bit' is set
            isPositive = false;
        }
        value[i] = this.setBuffer[i];
        value[i - 1] = this.setBuffer[i - 1];
    }
    if (!isPositive) {
        // fill leading bytes with 0xFF if the value is negative
        for (int i = 0; i < value.length; i++) {
            if (value[i] != 0) {
                break;
            }
            value[i] = (byte) 0xff;
        }
    }
    // int bitLength = getBitLength(type);
    // System.out.println(bitLength + " - " + bytesToHex(value));
    Object valueObj = BitUtils.toObject(this.channelDoc.getTypeOpt().get(), value);
    Channel channel = this.getChannel();
    if (channel instanceof ConfigChannel<?>) {
        // it is a ConfigChannel -> write directly
        ConfigChannel<?> configChannel = (ConfigChannel<?>) channel;
        configChannel.updateValue(valueObj, true);
        log.info("Updated [" + this.channelAddress + "] to [" + valueObj + "] via Modbus/TCP.");
    } else if (channel instanceof WriteChannel<?>) {
        // it is a WriteChannel -> handle by ApiWorker
        WriteChannel<?> writeChannel = (WriteChannel<?>) channel;
        WritePOJO writeObject = new WritePOJO(valueObj);
        apiWorker.addValue(writeChannel, writeObject);
    }
}
Also used : ConfigChannel(io.openems.api.channel.ConfigChannel) WriteChannel(io.openems.api.channel.WriteChannel) ConfigChannel(io.openems.api.channel.ConfigChannel) Channel(io.openems.api.channel.Channel) WriteChannel(io.openems.api.channel.WriteChannel) WritePOJO(io.openems.core.utilities.api.WritePOJO)

Example 5 with WriteChannel

use of io.openems.api.channel.WriteChannel in project openems by OpenEMS.

the class ThingRepository method thingChannelsUpdated.

@Override
public void thingChannelsUpdated(Thing thing) {
    // remove Channels from thingChannels, thingWriteChannels
    Databus databus = Databus.getInstance();
    Set<Entry<String, Channel>> thingRow = thingChannels.row(thing).entrySet();
    Iterator<Entry<String, Channel>> i = thingRow.iterator();
    while (i.hasNext()) {
        Entry<String, Channel> thingChannel = i.next();
        if (!(thingChannel.getValue() instanceof ConfigChannel)) {
            thingChannel.getValue().removeChangeListener(databus);
            thingChannel.getValue().removeUpdateListener(databus);
            i.remove();
        }
    }
    thingWriteChannels.removeAll(thing);
    // Add Channels to thingChannels, thingConfigChannels and thingWriteChannels
    ThingDoc thingDoc = classRepository.getThingDoc(thing.getClass());
    for (ChannelDoc channelDoc : thingDoc.getChannelDocs()) {
        Member member = channelDoc.getMember();
        try {
            List<Channel> channels = new ArrayList<>();
            boolean ignoreEmpty = false;
            if (member instanceof Method) {
                if (((Method) member).getReturnType().isArray()) {
                    // ignore e.g. if getFaultChannels is returning an empty array
                    ignoreEmpty = true;
                    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 (!ignoreEmpty && channels.isEmpty()) {
                log.warn("Channel is returning null! Thing [" + thing.id() + "], Member [" + member.getName() + "]");
                continue;
            }
            for (Channel channel : channels) {
                if (channel != null) {
                    // Add Channel to thingChannels
                    thingChannels.put(thing, channel.id(), channel);
                    // Add Channel to writeChannels
                    if (channel instanceof WriteChannel) {
                        thingWriteChannels.put(thing, (WriteChannel<?>) channel);
                    }
                    // Register Databus as listener
                    if (channel instanceof ReadChannel) {
                        ((ReadChannel<?>) channel).addUpdateListener(databus);
                        ((ReadChannel<?>) channel).addChangeListener(databus);
                    }
                }
            }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            log.warn("Unable to add Channel. Member [" + member.getName() + "]", e);
        }
    }
}
Also used : ConfigChannel(io.openems.api.channel.ConfigChannel) 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) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ChannelDoc(io.openems.api.doc.ChannelDoc) InvocationTargetException(java.lang.reflect.InvocationTargetException) ReadChannel(io.openems.api.channel.ReadChannel) Field(java.lang.reflect.Field) Entry(java.util.Map.Entry) WriteChannel(io.openems.api.channel.WriteChannel) Member(java.lang.reflect.Member) ThingDoc(io.openems.api.doc.ThingDoc)

Aggregations

WriteChannel (io.openems.api.channel.WriteChannel)6 ConfigChannel (io.openems.api.channel.ConfigChannel)5 Channel (io.openems.api.channel.Channel)4 JsonElement (com.google.gson.JsonElement)3 ArrayList (java.util.ArrayList)3 OpenemsException (io.openems.common.exceptions.OpenemsException)2 WriteJsonObject (io.openems.core.utilities.api.WriteJsonObject)2 WriteObject (io.openems.core.utilities.api.WriteObject)2 HashMap (java.util.HashMap)2 JsonArray (com.google.gson.JsonArray)1 JsonObject (com.google.gson.JsonObject)1 ReadChannel (io.openems.api.channel.ReadChannel)1 ThingStateChannel (io.openems.api.channel.ThingStateChannel)1 ChannelDoc (io.openems.api.doc.ChannelDoc)1 ThingDoc (io.openems.api.doc.ThingDoc)1 InvalidValueException (io.openems.api.exception.InvalidValueException)1 ReflectionException (io.openems.api.exception.ReflectionException)1 NotImplementedException (io.openems.common.exceptions.NotImplementedException)1 ApiWorker (io.openems.core.utilities.api.ApiWorker)1 WritePOJO (io.openems.core.utilities.api.WritePOJO)1