100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added EnergyOptimisationService.java (WIP) and fixed broken tests
Rich Turner3ade25dd983f
diff --git a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.javanew file mode 100644index 000000000..65f01b979--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java@@ -0,0 +1,487 @@+/*+ * Copyright 2021, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.energy;++import org.apache.camel.builder.RouteBuilder;+import org.openremote.container.message.MessageBrokerService;+import org.openremote.container.persistence.PersistenceEvent;+import org.openremote.container.timer.TimerService;+import org.openremote.manager.asset.AssetProcessingService;+import org.openremote.manager.asset.AssetStorageService;+import org.openremote.manager.datapoint.AssetPredictedDatapointService;+import org.openremote.manager.event.ClientEventService;+import org.openremote.manager.gateway.GatewayService;+import org.openremote.model.Container;+import org.openremote.model.ContainerService;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetDescriptor;+import org.openremote.model.asset.impl.*;+import org.openremote.model.attribute.Attribute;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.datapoint.ValueDatapoint;+import org.openremote.model.query.AssetQuery;+import org.openremote.model.util.AssetModelUtil;+import org.openremote.model.util.Pair;+import org.openremote.model.value.MetaItemType;++import java.time.Duration;+import java.time.Instant;+import java.time.ZoneId;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.time.temporal.ChronoUnit;+import java.util.*;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;+import java.util.function.BiFunction;+import java.util.function.Function;+import java.util.logging.Level;+import java.util.logging.Logger;+import java.util.stream.Collectors;+import java.util.stream.IntStream;++import static java.time.temporal.ChronoUnit.HOURS;+import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;+import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForEntityType;+import static org.openremote.manager.gateway.GatewayService.isNotForGateway;++/**+ * Handles optimisation instances for {@link EnergyOptimisationAsset}.+ */+public class EnergyOptimisationService extends RouteBuilder implements ContainerService {++ protected static final Logger LOG = Logger.getLogger(EnergyOptimisationService.class.getName());+ protected DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC));+ protected TimerService timerService;+ protected AssetProcessingService assetProcessingService;+ protected AssetStorageService assetStorageService;+ protected AssetPredictedDatapointService assetPredictedDatapointService;+ protected MessageBrokerService messageBrokerService;+ protected ClientEventService clientEventService;+ protected GatewayService gatewayService;+ protected ScheduledExecutorService executorService;+ protected Map<String, Pair<EnergyOptimiser, ScheduledFuture<?>>> assetEnergyOptimiserMap = new HashMap<>();++ @Override+ public int getPriority() {+ return DEFAULT_PRIORITY;+ }++ @Override+ public void init(Container container) throws Exception {+ timerService = container.getService(TimerService.class);+ assetPredictedDatapointService = container.getService(AssetPredictedDatapointService.class);+ assetProcessingService = container.getService(AssetProcessingService.class);+ assetStorageService = container.getService(AssetStorageService.class);+ messageBrokerService = container.getService(MessageBrokerService.class);+ clientEventService = container.getService(ClientEventService.class);+ gatewayService = container.getService(GatewayService.class);+ executorService = container.getExecutorService();++ clientEventService.addInternalSubscription(+ AttributeEvent.class,+ null,+ this::onAssetAttributeEvent+ );+ }++ @Override+ public void start(Container container) throws Exception {+ container.getService(MessageBrokerService.class).getContext().addRoutes(this);++ // Load all enabled optimisation assets and instantiate an optimiser for each+ LOG.fine("Loading optimisation assets...");++ List<EnergyOptimisationAsset> energyOptimisationAssets = assetStorageService.findAll(+ new AssetQuery()+ .select(new AssetQuery.Select().excludeParentInfo(true))+ .types(EnergyOptimisationAsset.class)+ )+ .stream()+ .map(asset -> (EnergyOptimisationAsset) asset)+ .filter(optimisationAsset -> !optimisationAsset.isOptimisationDisabled().orElse(false))+ .collect(Collectors.toList());++ LOG.fine("Found enabled optimisation asset count = " + energyOptimisationAssets.size());++ energyOptimisationAssets.forEach(this::startOptimisation);+ }++ @SuppressWarnings("unchecked")+ @Override+ public void configure() throws Exception {+ from(PERSISTENCE_TOPIC)+ .routeId("EnergyOptimisationAssetPersistenceChanges")+ .filter(isPersistenceEventForEntityType(EnergyOptimisationAsset.class))+ .filter(isNotForGateway(gatewayService))+ .process(exchange -> processAssetChange((PersistenceEvent<EnergyOptimisationAsset>) exchange.getIn().getBody(PersistenceEvent.class)));+ }++ @Override+ public void stop(Container container) throws Exception {+ new ArrayList<>(assetEnergyOptimiserMap.keySet())+ .forEach(this::stopOptimisation);+ }++ protected void processAssetChange(PersistenceEvent<EnergyOptimisationAsset> persistenceEvent) {++ }++ protected void onAssetAttributeEvent(AttributeEvent attributeEvent) {++ }+++ protected void startOptimisation(EnergyOptimisationAsset optimisationAsset) {+ LOG.fine("Initialising optimiser for optimisation asset: " + optimisationAsset);+ double intervalSize = optimisationAsset.getIntervalSize().orElse(0.25d);+ int financialWeighting = optimisationAsset.getFinancialWeighting().orElse(100);++ try {+ EnergyOptimiser optimiser = new EnergyOptimiser(intervalSize, ((double) financialWeighting) / 100);+ ScheduledFuture<?> runScheduler = scheduleOptimisation(optimisationAsset.getId(), optimiser);+ assetEnergyOptimiserMap.put(optimisationAsset.getId(), new Pair<>(optimiser, runScheduler));+ } catch (IllegalArgumentException e) {+ LOG.log(Level.SEVERE, "Failed to start energy optimiser for asset: " + optimisationAsset, e);+ }+ }++ protected void stopOptimisation(String optimisationAssetId) {+ Pair<EnergyOptimiser, ScheduledFuture<?>> optimiserAndScheduler = assetEnergyOptimiserMap.remove(optimisationAssetId);++ if (optimiserAndScheduler == null) {+ return;+ }++ LOG.fine("Removing optimiser for optimisation asset: " + optimisationAssetId);++ optimiserAndScheduler.value.cancel(false);+ }+++ /**+ * Schedules execution of the optimiser at the start of the interval window with up to 30s of offset randomness+ * added so that multiple optimisers don't all run at exactly the same instance; the interval execution times are+ * calculated relative to the hour. e.g. a 0.25h intervalSize (15min) would execute at NN:00+offset, NN:15+offset,+ * NN:30+offset, NN:45+offset...It is important that intervals coincide with any change in supplier tariff so that+ * the optimisation works effectively.+ */+ protected ScheduledFuture<?> scheduleOptimisation(String optimisationAssetId, EnergyOptimiser optimiser) throws IllegalStateException {++ if (optimiser == null) {+ throw new IllegalStateException("Optimiser instance not found for asset: " + optimisationAssetId);+ }++ long periodSeconds = (long) (optimiser.intervalSize * 60 * 60);++ if (periodSeconds < 300) {+ throw new IllegalStateException("Optimiser interval size is too small (minimum is 5 mins) for asset: " + optimisationAssetId);+ }++ long currentMillis = timerService.getCurrentTimeMillis();+ Instant optimisationStartTime = getOptimisationStartTime(currentMillis, periodSeconds);++ // Execute first optimisation at this period to initialise the system+ runOptimisation(optimisationAssetId, optimisationStartTime);++ // Schedule subsequent runs+ long offsetSeconds = (long) (Math.random() * 30);+ Duration startDuration = Duration.between(Instant.ofEpochMilli(currentMillis), optimisationStartTime.plus(offsetSeconds, ChronoUnit.SECONDS));++ return executorService.scheduleAtFixedRate(() ->+ runOptimisation(optimisationAssetId, Instant.ofEpochMilli(timerService.getCurrentTimeMillis()).truncatedTo(ChronoUnit.MINUTES)),+ startDuration.getSeconds(),+ periodSeconds,+ TimeUnit.SECONDS);+ }++ protected static Instant getOptimisationStartTime(long currentMillis, long periodSeconds) {+ Instant now = Instant.ofEpochMilli(currentMillis);++ Instant optimisationStartTime = Instant.ofEpochMilli(currentMillis)+ .minus(periodSeconds, ChronoUnit.SECONDS)+ .truncatedTo(ChronoUnit.HOURS);++ while (optimisationStartTime.isBefore(now)) {+ optimisationStartTime = optimisationStartTime.plus(periodSeconds, ChronoUnit.SECONDS);+ }++ // Move to one period before+ return optimisationStartTime.minus(periodSeconds, ChronoUnit.SECONDS);+ }++ /**+ * Runs the optimisation routine for the specified time; it is important that this method does not throw an+ * exception as it will cancel the scheduled task thus stopping future optimisations.+ */+ protected void runOptimisation(String optimisationAssetId, Instant optimisationTime) {+ Pair<EnergyOptimiser, ScheduledFuture<?>> optimiserAndScheduler = assetEnergyOptimiserMap.get(optimisationAssetId);++ if (optimiserAndScheduler == null) {+ return;+ }++ LOG.finer("Running optimiser for optimisation asset: " + optimisationAssetId + ", for time: " + formatter.format(optimisationTime));++ EnergyOptimiser optimiser = optimiserAndScheduler.key;+ int intervalCount = optimiser.get24HourIntervalCount();++ // Get all child assets+ List<Asset<?>> childElectricityAssets = assetStorageService.findAll(+ new AssetQuery()+ .select(new AssetQuery.Select().excludePath(true))+ .recursive(true)+ .parents(optimisationAssetId)+ );++ LOG.finest("Optimisation asset child asset count: " + childElectricityAssets.size());++ List<ElectricitySupplierAsset> supplierAssets = childElectricityAssets.stream()+ .filter(asset -> (asset instanceof ElectricitySupplierAsset) && asset.hasAttribute(ElectricitySupplierAsset.TARIFF_IMPORT))+ .map(asset -> (ElectricitySupplierAsset)asset)+ .collect(Collectors.toList());++ if (supplierAssets.size() != 1) {+ LOG.warning("Optimisation routine expects exactly one " + ElectricitySupplierAsset.class.getSimpleName() + " asset with a '" + ElectricitySupplierAsset.TARIFF_IMPORT.getName() + "' attribute but found: " + supplierAssets.size());+ return;+ }++ List<ElectricityStorageAsset> optimisableStorageAssets = childElectricityAssets.stream()+ .filter(asset -> (asset instanceof ElectricityStorageAsset)+ && asset.hasAttribute(ElectricityAsset.POWER_SETPOINT))+ .map(asset -> (ElectricityStorageAsset)asset)+ .sorted(Comparator.comparingInt(asset -> asset.getEnergyLevelSchedule().map(schedule -> 0).orElse(1)))+ .collect(Collectors.toList());++ if (optimisableStorageAssets.isEmpty()) {+ LOG.warning("Optimisation routine expects at least one " + ElectricityStorageAsset.class.getSimpleName() + " asset with a '" + ElectricityAsset.POWER_SETPOINT.getName() + "' attribute but found none");+ return;+ }++ // Get consumers and producers and sum power demand for the next 24hrs+ double[] powerNets = new double[intervalCount];++ childElectricityAssets.stream()+ .filter(asset ->+ // Filter consumers and producers or group asset of consumers and producers that have a power attribute+ asset instanceof ElectricityConsumerAsset+ || asset instanceof ElectricityProducerAsset+ || isProducerOrConsumerGroupAsset(asset))+ .filter(asset -> asset.hasAttribute(ElectricityAsset.POWER))+ .forEach(asset -> {+ @SuppressWarnings("OptionalGetWithoutIsPresent")+ Attribute<Double> powerAttribute = asset.getAttribute(ElectricityAsset.POWER).get();+ double[] powerLevels = get24HAttributeValues(asset.getId(), powerAttribute, optimiser.getIntervalSize(), intervalCount, optimisationTime);+ IntStream.range(0, intervalCount).forEach(i -> powerNets[i] += powerLevels[i]);+ });++ // Get supplier costs for each interval+ ElectricitySupplierAsset supplierAsset = supplierAssets.get(0);+ double financialWeightingImport = optimiser.getFinancialWeighting();+ double financialWeightingExport = optimiser.getFinancialWeighting();++ if (financialWeightingImport < 1d && !supplierAsset.getCarbonImport().isPresent()) {+ financialWeightingImport = 1d;+ }++ if (financialWeightingExport < 1d && !supplierAsset.getCarbonExport().isPresent()) {+ financialWeightingExport = 1d;+ }++ double[] costsImport = get24HAttributeValues(supplierAsset.getId(), supplierAsset.getAttribute(ElectricitySupplierAsset.TARIFF_IMPORT).orElse(null), optimiser.getIntervalSize(), intervalCount, optimisationTime);+ double[] costsExport = get24HAttributeValues(supplierAsset.getId(), supplierAsset.getAttribute(ElectricitySupplierAsset.TARIFF_EXPORT).orElse(null), optimiser.getIntervalSize(), intervalCount, optimisationTime);++ if (financialWeightingImport < 1d || financialWeightingExport < 1d) {+ double[] carbonImport = get24HAttributeValues(supplierAsset.getId(), supplierAsset.getAttribute(ElectricitySupplierAsset.CARBON_IMPORT).orElse(null), optimiser.getIntervalSize(), intervalCount, optimisationTime);+ double[] carbonExport = get24HAttributeValues(supplierAsset.getId(), supplierAsset.getAttribute(ElectricitySupplierAsset.CARBON_EXPORT).orElse(null), optimiser.getIntervalSize(), intervalCount, optimisationTime);+ for (int i = 0; i < costsImport.length; i++) {+ costsImport[i] += carbonImport[i];+ costsExport[i] += carbonExport[i];+ }+ }++ // Optimise storage assets with priority on storage assets with an energy schedule (already sorted above)+ double importPowerMax = Math.min(supplierAsset.getPowerImportMax().orElse(Double.MAX_VALUE), supplierAsset.getPowerImportMax().orElse(Double.MAX_VALUE));+ double exportPowerMax = -1 * Math.min(supplierAsset.getPowerExportMax().orElse(Double.MAX_VALUE), supplierAsset.getPowerExportMax().orElse(Double.MAX_VALUE));+ double[] importPowerMaxes = new double[intervalCount];+ double[] exportPowerMaxes = new double[intervalCount];+ Arrays.fill(importPowerMaxes, importPowerMax);+ Arrays.fill(exportPowerMaxes, exportPowerMax);+ long periodSeconds = (long)optimiser.getIntervalSize()*60*60;++ optimisableStorageAssets.forEach(storageAsset -> {+ LOG.finest("Optimising storage asset setpoints: " + storageAsset);+ double[] setpoints = getStoragePowerSetpoints(optimiser, storageAsset, powerNets, importPowerMaxes, exportPowerMaxes, costsImport, costsExport);++ // Assume these setpoints will be applied so update the power net values with these+ for (int i = 0; i < powerNets.length; i++) {+ powerNets[i] += setpoints[i];+ }++ // Push the setpoints into the prediction service for the storage asset's setpoint attribute and set current setpoint+ for (int i = 1; i < setpoints.length; i++) {+ assetPredictedDatapointService.updateValue(+ new AttributeRef(storageAsset.getId(), ElectricityAsset.POWER_SETPOINT.getName()),+ setpoints[i],+ optimisationTime.plus(periodSeconds*i, ChronoUnit.SECONDS).toEpochMilli());+ }+ assetProcessingService.sendAttributeEvent(new AttributeEvent(storageAsset.getId(), ElectricityAsset.POWER_SETPOINT, setpoints[0]));+ });++ }++ protected boolean isProducerOrConsumerGroupAsset(Asset<?> asset) {+ if (!(asset instanceof GroupAsset)) {+ return false;+ }++ Class<?> assetClass = AssetModelUtil+ .getAssetDescriptor(((GroupAsset)asset).getChildAssetType().orElse(null))+ .map(AssetDescriptor::getType)+ .orElse(null);++ return assetClass != null &&+ (ElectricityConsumerAsset.class.isAssignableFrom(assetClass)+ || ElectricityProducerAsset.class.isAssignableFrom(assetClass));+ }++ protected double[] get24HAttributeValues(String assetId, Attribute<Double> attribute, double intervalSize, int intervalCount, Instant optimisationTime) {++ double[] values = new double[intervalCount];++ if (attribute == null) {+ return values;+ }++ AttributeRef ref = new AttributeRef(assetId, attribute.getName());++ if (attribute.hasMeta(MetaItemType.HAS_PREDICTED_DATA_POINTS)) {+ ValueDatapoint<?>[] predictedData = assetPredictedDatapointService.getValueDatapoints(+ ref,+ "minute",+ ((long) intervalSize * 60) + " minute",+ optimisationTime.toEpochMilli(), optimisationTime.plus(24, HOURS).toEpochMilli()+ );+ if (predictedData.length != values.length) {+ LOG.warning("Returned predicted data point count does not match interval count: Ref=" + ref + ", expected=" + values.length + ", actual=" + predictedData.length);+ } else {+ IntStream.range(0, predictedData.length).forEach(i ->+ values[i] = (double)(Object)predictedData[i].getValue());+ }+ } else {+ LOG.fine("Electricity asset doesn't have any predicted data for attribute: Ref=" + ref);+ }++ values[0] = attribute.getValue().orElse(0d);+ return values;+ }++ /**+ * Returns the power setpoint calculator for the specified asset (for producers power demand will only ever be+ * negative, for consumers it will only ever be positive and for storage assets that support export (i.e. supports+ * producer and consumer) it can be positive or negative at a given interval. For this to work the supplied+ * parameters should be updated when the system changes and not replaced so that references maintained by the+ * calculator are valid and up to date.+ */+ protected double[] getStoragePowerSetpoints(EnergyOptimiser optimiser, ElectricityStorageAsset storageAsset, double[] powerNets, double[] importPowerLimits, double[] exportPowerLimits, double[] costImports, double[] costExports) {++ int intervalCount = powerNets.length;+ boolean hasSetpoint = storageAsset.hasAttribute(ElectricityStorageAsset.POWER_SETPOINT);+ boolean supportsExport = storageAsset.isSupportsExport().orElse(false);+ boolean supportsImport = storageAsset.isSupportsImport().orElse(false);++ if (!supportsExport && !supportsImport) {+ LOG.info("Storage asset doesn't support import or export: " + storageAsset.getId());+ return new double[intervalCount];+ }++ if (!hasSetpoint) {+ LOG.info("Storage asset has no '" + ElectricityStorageAsset.POWER_SETPOINT.getName() + "' attribute so cannot be controlled: " + storageAsset.getId());+ return new double[intervalCount];+ }++ double energyCapacity = storageAsset.getEnergyCapacity().orElse(0d);+ double energyLevel = Math.min(energyCapacity, storageAsset.getEnergyLevel().orElse(-1d));++ if (energyCapacity <= 0d || energyLevel < 0) {+ LOG.info("Storage asset has no capacity or energy level so cannot import or export energy: " + storageAsset.getId());+ return new double[intervalCount];+ }++ double energyLevelMax = Math.min(energyCapacity, ((double) storageAsset.getEnergyLevelPercentageMax().orElse(100) / 100) * energyCapacity);+ double energyLevelMin = Math.min(energyCapacity, ((double) storageAsset.getEnergyLevelPercentageMin().orElse(0) / 100) * energyCapacity);+ double[] energyLevelMins = new double[intervalCount];++ // Does the storage support import and have an energy level schedule+ Optional<Integer[][]> energyLevelScheduleOptional = storageAsset.getEnergyLevelSchedule();+ boolean hasEnergyMinRequirement = energyLevelMin > 0 || energyLevelScheduleOptional.isPresent();+ double powerExportMax = storageAsset.getPowerExportMax().orElse(Double.MIN_VALUE);+ double powerImportMax = storageAsset.getPowerImportMax().orElse(Double.MAX_VALUE);+ int[][] energySchedule = energyLevelScheduleOptional.map(dayArr -> Arrays.stream(dayArr).map(hourArr -> Arrays.stream(hourArr).mapToInt(Integer::intValue).toArray()).toArray(int[][]::new)).orElse(null);++ optimiser.applyEnergySchedule(energyLevelMins, energyCapacity, energyLevelMin, energyLevelMax, energySchedule, timerService.getCurrentTimeMillis());++ // TODO: Make these a function of energy level+ Function<Integer, Double> powerImportMaxCalculator = interval -> powerImportMax;+ Function<Integer, Double> powerExportMaxCalculator = interval -> powerExportMax;++ if (hasEnergyMinRequirement) {+ optimiser.normaliseEnergyMinRequirements(energyLevelMins, powerImportMaxCalculator, powerExportMaxCalculator, energyLevel);+ }++ double[][] exportCostAndPower = null;+ double[][] importCostAndPower = null;+ double[] powerSetpoints = new double[intervalCount];++ Function<Integer, Double> energyLevelCalculator = interval ->+ Math.min(+ energyLevelMax,+ energyLevel + IntStream.range(0, interval).mapToDouble(j -> powerSetpoints[j] * optimiser.getIntervalSize()).sum()+ );++ // If asset supports exporting energy (V2G, battery storage, etc.) then need to determine if there are+ // opportunities to export energy to save/earn, taking into consideration the cost of exporting from this asset+ if (supportsExport) {+ // Find intervals that save/earn by exporting energy from this storage asset by looking at power levels+ BiFunction<Integer, Double, double[]> exportOptimiser = optimiser.getExportOptimiser(powerNets, exportPowerLimits, costImports, costExports, storageAsset.getTariffExport().orElse(0d));+ exportCostAndPower = IntStream.range(0, intervalCount).mapToObj(it -> exportOptimiser.apply(it, powerExportMax))+ .toArray(double[][]::new);+ }++ // If asset supports importing energy then need to determine if there are opportunities to import energy to+ // save/earn, taking into consideration the cost of importing to this asset, also need to ensure that min+ // energy demands are met.+ if (supportsImport) {+ BiFunction<Integer, double[], double[]> importOptimiser = optimiser.getImportOptimiser(powerNets, importPowerLimits, costImports, costExports, storageAsset.getTariffImport().orElse(0d));+ importCostAndPower = IntStream.range(0, intervalCount).mapToObj(it -> importOptimiser.apply(it, new double[]{0d, powerImportMax}))+ .toArray(double[][]::new);++ if (hasEnergyMinRequirement) {+ optimiser.applyEnergyMinImports(importCostAndPower, energyLevelMins, powerSetpoints, energyLevelCalculator, importOptimiser, powerImportMaxCalculator);+ }+ }++ optimiser.applyEarningOpportunities(importCostAndPower, exportCostAndPower, energyLevelMins, powerSetpoints, energyLevelCalculator, powerImportMaxCalculator, powerExportMaxCalculator, energyLevelMax);++ return powerSetpoints;+ }+}diff --git a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimiser.java b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimiser.javaindex 8aa609ad7..feb372711 100644--- a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimiser.java+++ b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimiser.java@@ -19,11 +19,7 @@*/package org.openremote.manager.energy;-import org.openremote.model.asset.impl.ElectricityAsset;-import org.openremote.model.asset.impl.ElectricityConsumerAsset;-import org.openremote.model.asset.impl.ElectricityProducerAsset;import org.openremote.model.asset.impl.ElectricityStorageAsset;-import org.openremote.model.attribute.AttributeRef;import org.openremote.model.util.Pair;import java.time.Instant;@@ -34,63 +30,34 @@ import java.util.*;import java.util.concurrent.atomic.AtomicInteger;import java.util.function.BiFunction;import java.util.function.Function;-import java.util.function.Supplier;import java.util.logging.Logger;import java.util.stream.Collectors;import java.util.stream.IntStream;public class EnergyOptimiser {- /**- * A comparator for sorting {@link ElectricityAsset}s ready for power optimisation calculations; consumers/producers- * that cannot be optimised have the highest priority as they cannot be influenced in any way; consumers that can be- * optimised should then be next followed by producers that can be optimised. Storage assets should have the lowest- * priority as they can potentially adapt to the demands of the other assets.- */- public static final Comparator<ElectricityAsset<?>> assetComparator = Comparator.comparingInt(asset -> {- if (asset instanceof ElectricityStorageAsset) {- if (((ElectricityStorageAsset) asset).isSupportsExport().orElse(false)) {- return 20000;- }-- return 10000;- }-- if (asset instanceof ElectricityProducerAsset) {- return 1000;- }-- return 2000;- });private static final Logger LOG = Logger.getLogger(EnergyOptimiser.class.getName());protected double intervalSize;protected double financialWeighting;- protected Supplier<Long> currentMillisSupplier;- Function<AttributeRef, double[]> predictedDataSupplier;/*** 24 divided by intervalSize must be a whole number*/- public EnergyOptimiser(double intervalSize, double financialWeighting, Function<AttributeRef, double[]> predictedDataSupplier, Supplier<Long> currentMillisSupplier) {+ public EnergyOptimiser(double intervalSize, double financialWeighting) throws IllegalArgumentException {if ((24d / intervalSize) != (int) (24d / intervalSize)) {throw new IllegalArgumentException("24 divided by intervalSizeHours must be whole number");}this.intervalSize = intervalSize;this.financialWeighting = Math.max(0, Math.min(1d, financialWeighting));- this.predictedDataSupplier = predictedDataSupplier;- this.currentMillisSupplier = currentMillisSupplier;}-// public double[] getGridImportCosts(ElectricitySupplierAsset asset) {-//-// }-//-// /**-// * Function to calculate the powerMaxExport for the given asset at interval n-// */-// public Function<Integer, Double> getPowerExportMaxCalculator(ElectricityAsset<?> asset) {-//-// }+ public double getIntervalSize() {+ return intervalSize;+ }++ public double getFinancialWeighting() {+ return financialWeighting;+ }public int get24HourIntervalCount() {return (int) (24d / intervalSize);@@ -211,112 +178,6 @@ public class EnergyOptimiser {// };// }- /**- * Returns the power setpoint calculator for the specified asset (for producers power demand will only ever be- * negative, for consumers it will only ever be positive and for storage assets that support export (i.e. supports- * producer and consumer) it can be positive or negative at a given interval. For this to work the supplied- * parameters should be updated when the system changes and not replaced so that references maintained by the- * calculator are valid and up to date.- */- public Supplier<double[]> getPowerSetpointCalculator(ElectricityAsset<?> asset, double[] powerNets, double[] powerNetLimits, double[] tariffImports, double[] tariffExports) {-- int intervalCount = get24HourIntervalCount();-- if (asset instanceof ElectricityProducerAsset- || asset instanceof ElectricityConsumerAsset) {- // Get predicted data from prediction provider- return () -> predictedDataSupplier.apply(new AttributeRef(asset.getId(), ElectricityProducerAsset.POWER.getName()));- }-- if (!(asset instanceof ElectricityStorageAsset)) {- return () -> new double[intervalCount];- }-- ElectricityStorageAsset storageAsset = (ElectricityStorageAsset) asset;- boolean hasSetpoint = storageAsset.hasAttribute(ElectricityStorageAsset.POWER_SETPOINT);- boolean supportsExport = storageAsset.isSupportsExport().orElse(false);- boolean supportsImport = storageAsset.isSupportsImport().orElse(false);--- if (!supportsExport && !supportsImport) {- LOG.info("Storage asset doesn't support import or export: " + asset.getId());- return () -> new double[intervalCount];- }-- if (!hasSetpoint) {- LOG.info("Storage asset has no setpoint attribute so cannot be controlled: " + asset.getId());- return () -> new double[intervalCount];- }-- return () -> {-- double energyCapacity = storageAsset.getEnergyCapacity().orElse(0d);- double energyLevel = Math.min(energyCapacity, storageAsset.getEnergyLevel().orElse(-1d));-- if (energyCapacity <= 0d || energyLevel < 0) {- LOG.info("Storage asset has no capacity or energy level so cannot import or export energy: " + asset.getId());- return new double[intervalCount];- }-- double energyLevelMax = Math.min(energyCapacity, ((double) storageAsset.getEnergyLevelPercentageMax().orElse(100) / 100) * energyCapacity);- double energyLevelMin = Math.min(energyCapacity, ((double) storageAsset.getEnergyLevelPercentageMin().orElse(0) / 100) * energyCapacity);- double[] energyLevelMins = new double[intervalCount];-- // Does the storage support import and have an energy level schedule- Optional<Integer[][]> energyLevelScheduleOptional = storageAsset.getEnergyLevelSchedule();- boolean hasEnergyMinRequirement = energyLevelMin > 0 || energyLevelScheduleOptional.isPresent();- double powerExportMax = storageAsset.getPowerExportMax().orElse(Double.MIN_VALUE);- double powerImportMax = storageAsset.getPowerImportMax().orElse(Double.MAX_VALUE);- int[][] energySchedule = energyLevelScheduleOptional.map(dayArr -> Arrays.stream(dayArr).map(hourArr -> Arrays.stream(hourArr).mapToInt(Integer::intValue).toArray()).toArray(int[][]::new)).orElse(null);-- applyEnergySchedule(energyLevelMins, energyCapacity, energyLevelMin, energyLevelMax, energySchedule, currentMillisSupplier.get());-- // TODO: Make these a function of energy level- Function<Integer, Double> powerImportMaxCalculator = interval -> powerImportMax;- Function<Integer, Double> powerExportMaxCalculator = interval -> powerExportMax;-- if (hasEnergyMinRequirement) {- normaliseEnergyMinRequirements(energyLevelMins, powerImportMaxCalculator, powerExportMaxCalculator, energyLevel);- }-- double[][] exportCostAndPower = null;- double[][] importCostAndPower = null;- double[] powerSetpoints = new double[intervalCount];-- Function<Integer, Double> energyLevelCalculator = interval ->- Math.min(- energyLevelMax,- energyLevel + IntStream.range(0, interval).mapToDouble(j -> powerSetpoints[j] * intervalSize).sum()- );-- // If asset supports exporting energy (V2G, battery storage, etc.) then need to determine if there are- // opportunities to export energy to save/earn, taking into consideration the cost of exporting from this asset- if (supportsExport) {- // Find intervals that save/earn by exporting energy from this storage asset by looking at power levels- BiFunction<Integer, Double, double[]> exportOptimiser = getExportOptimiser(powerNets, powerNetLimits, tariffImports, tariffExports, asset.getTariffExport().orElse(0d));- exportCostAndPower = IntStream.range(0, intervalCount).mapToObj(it -> exportOptimiser.apply(it, powerExportMax))- .toArray(double[][]::new);- }-- // If asset supports importing energy then need to determine if there are opportunities to import energy to- // save/earn, taking into consideration the cost of importing to this asset, also need to ensure that min- // energy demands are met.- if (supportsImport) {- BiFunction<Integer, double[], double[]> importOptimiser = getImportOptimiser(powerNets, powerNetLimits, tariffImports, tariffExports, asset.getTariffImport().orElse(0d));- importCostAndPower = IntStream.range(0, intervalCount).mapToObj(it -> importOptimiser.apply(it, new double[]{0d, powerImportMax}))- .toArray(double[][]::new);-- if (hasEnergyMinRequirement) {- applyEnergyMinImports(importCostAndPower, energyLevelMins, powerSetpoints, energyLevelCalculator, importOptimiser, powerImportMaxCalculator);- }- }-- applyEarningOpportunities(importCostAndPower, exportCostAndPower, energyLevelMins, powerSetpoints, energyLevelCalculator, powerImportMaxCalculator, powerExportMaxCalculator, energyLevelMax);-- return powerSetpoints;- };- }-/*** Will take the supplied 24x7 energy schedule percentages and energy level min/max values and apply them to the* supplied energyLevelMins also adjusting for any intervalSize difference.diff --git a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerServiceindex 155a96b1b..a4e799ed9 100644--- a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService+++ b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService@@ -25,3 +25,4 @@ org.openremote.manager.gateway.GatewayServiceorg.openremote.manager.gateway.GatewayClientServiceorg.openremote.manager.mqtt.MqttBrokerServiceorg.openremote.manager.asset.AssetModelService+org.openremote.manager.energy.EnergyOptimisationServicediff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricVehicleAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricVehicleAsset.javaindex f63754d89..67bfe90f5 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricVehicleAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricVehicleAsset.java@@ -229,42 +229,6 @@ public class ElectricVehicleAsset extends ElectricityBatteryAsset {return this;}- @Override- public ElectricVehicleAsset setTariffImport(Double value) {- super.setTariffImport(value);- return this;- }-- @Override- public ElectricVehicleAsset setTariffExport(Double value) {- super.setTariffExport(value);- return this;- }-- @Override- public ElectricVehicleAsset setCarbonImport(Double value) {- super.setCarbonImport(value);- return this;- }-- @Override- public ElectricVehicleAsset setCarbonExport(Double value) {- super.setCarbonExport(value);- return this;- }-- @Override- public ElectricVehicleAsset setCarbonImportTotal(Integer value) {- super.setCarbonImportTotal(value);- return this;- }-- @Override- public ElectricVehicleAsset setCarbonExportTotal(Integer value) {- super.setCarbonExportTotal(value);- return this;- }-@Overridepublic ElectricVehicleAsset setId(String id) {super.setId(id);diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityAsset.javaindex 1af6617ea..6f5c73be8 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityAsset.java@@ -34,7 +34,7 @@ public abstract class ElectricityAsset<T extends ElectricityAsset<?>> extends Asnew MetaItem<>(MetaItemType.READ_ONLY)).withUnits(UNITS_KILO, UNITS_WATT);public static final AttributeDescriptor<Double> POWER_SETPOINT = new AttributeDescriptor<>("powerSetpoint", ValueType.NUMBER)- .withUnits(UNITS_KILO, UNITS_WATT).withFormat(ValueFormat.NUMBER_1_DP());+ .withUnits(UNITS_KILO, UNITS_WATT).withFormat(ValueFormat.NUMBER_1_DP()).withOptional(true);public static final AttributeDescriptor<Double> POWER_IMPORT_MIN = new AttributeDescriptor<>("powerImportMin", ValueType.POSITIVE_NUMBER).withUnits(UNITS_KILO, UNITS_WATT);public static final AttributeDescriptor<Double> POWER_IMPORT_MAX = new AttributeDescriptor<>("powerImportMax", ValueType.POSITIVE_NUMBER)@@ -56,21 +56,10 @@ public abstract class ElectricityAsset<T extends ElectricityAsset<?>> extends Aspublic static final AttributeDescriptor<Integer> EFFICIENCY_EXPORT = new AttributeDescriptor<>("efficiencyExport", ValueType.POSITIVE_INTEGER).withUnits(UNITS_PERCENTAGE).withConstraints(new ValueConstraint.Min(0), new ValueConstraint.Max(100));-public static final AttributeDescriptor<Double> TARIFF_IMPORT = new AttributeDescriptor<>("tariffImport", ValueType.NUMBER)- .withUnits("EUR", UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR);+ .withUnits("EUR", UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR).withOptional(true);public static final AttributeDescriptor<Double> TARIFF_EXPORT = new AttributeDescriptor<>("tariffExport", ValueType.NUMBER)- .withUnits("EUR", UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR);- public static final AttributeDescriptor<Double> CARBON_IMPORT = new AttributeDescriptor<>("carbonImport", ValueType.NUMBER)- .withUnits(UNITS_KILO, UNITS_GRAM, UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR);- public static final AttributeDescriptor<Double> CARBON_EXPORT = new AttributeDescriptor<>("carbonExport", ValueType.NUMBER)- .withUnits(UNITS_KILO, UNITS_GRAM, UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR).withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = new AttributeDescriptor<>("carbonImportTotal", ValueType.POSITIVE_INTEGER,- new MetaItem<>(MetaItemType.READ_ONLY, true)- ).withUnits(UNITS_KILO, UNITS_GRAM);- public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = new AttributeDescriptor<>("carbonExportTotal", ValueType.POSITIVE_INTEGER,- new MetaItem<>(MetaItemType.READ_ONLY, true)- ).withUnits(UNITS_KILO, UNITS_GRAM);+ .withUnits("EUR", UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR).withOptional(true);/*** For use by hydrators (i.e. JPA/Jackson)@@ -180,7 +169,7 @@ public abstract class ElectricityAsset<T extends ElectricityAsset<?>> extends AsgetAttributes().getOrCreate(TARIFF_IMPORT).setValue(value);return (T)this;}-+public Optional<Double> getTariffExport() {return getAttributes().getValue(TARIFF_EXPORT);}@@ -189,40 +178,4 @@ public abstract class ElectricityAsset<T extends ElectricityAsset<?>> extends AsgetAttributes().getOrCreate(TARIFF_EXPORT).setValue(value);return (T)this;}-- public Optional<Double> getCarbonImport() {- return getAttributes().getValue(CARBON_IMPORT);- }-- public T setCarbonImport(Double value) {- getAttributes().getOrCreate(CARBON_IMPORT).setValue(value);- return (T)this;- }-- public Optional<Double> getCarbonExport() {- return getAttributes().getValue(CARBON_EXPORT);- }-- public T setCarbonExport(Double value) {- getAttributes().getOrCreate(CARBON_EXPORT).setValue(value);- return (T)this;- }-- public Optional<Integer> getCarbonImportTotal() {- return getAttributes().getValue(CARBON_IMPORT_TOTAL);- }-- public T setCarbonImportTotal(Integer value) {- getAttributes().getOrCreate(CARBON_IMPORT_TOTAL).setValue(value);- return (T)this;- }-- public Optional<Integer> getCarbonExportTotal() {- return getAttributes().getValue(CARBON_EXPORT_TOTAL);- }-- public T setCarbonExportTotal(Integer value) {- getAttributes().getOrCreate(CARBON_EXPORT_TOTAL).setValue(value);- return (T)this;- }}diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityChargerAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityChargerAsset.javaindex 0f24e98cf..911d68bfb 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityChargerAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityChargerAsset.java@@ -60,11 +60,11 @@ public class ElectricityChargerAsset extends ElectricityStorageAsset {public static final AttributeDescriptor<Integer> ENERGY_LEVEL_PERCENTAGE_MIN = ElectricityStorageAsset.ENERGY_LEVEL_PERCENTAGE_MIN.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_IMPORT = ElectricityAsset.EFFICIENCY_IMPORT.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_EXPORT = ElectricityAsset.EFFICIENCY_EXPORT.withOptional(true);- public static final AttributeDescriptor<Double> TARIFF_IMPORT = ElectricityAsset.TARIFF_IMPORT.withOptional(true);- public static final AttributeDescriptor<Double> TARIFF_EXPORT = ElectricityAsset.TARIFF_EXPORT.withOptional(true);- public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricityAsset.CARBON_IMPORT.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricityAsset.CARBON_IMPORT_TOTAL.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricityAsset.CARBON_EXPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Double> TARIFF_IMPORT = ElectricitySupplierAsset.TARIFF_IMPORT.withOptional(true);+ public static final AttributeDescriptor<Double> TARIFF_EXPORT = ElectricitySupplierAsset.TARIFF_EXPORT.withOptional(true);+ public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricitySupplierAsset.CARBON_IMPORT.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricitySupplierAsset.CARBON_IMPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricitySupplierAsset.CARBON_EXPORT_TOTAL.withOptional(true);public static final AssetDescriptor<ElectricityChargerAsset> DESCRIPTOR = new AssetDescriptor<>("ev-station", "8A293D", ElectricityChargerAsset.class);diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityConsumerAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityConsumerAsset.javaindex fdee414c0..5b562259e 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityConsumerAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityConsumerAsset.java@@ -20,14 +20,10 @@package org.openremote.model.asset.impl;import org.openremote.model.asset.AssetDescriptor;-import org.openremote.model.attribute.MetaItem;import org.openremote.model.value.*;import javax.persistence.Entity;-import static org.openremote.model.Constants.*;-import static org.openremote.model.Constants.UNITS_GRAM;-@Entitypublic class ElectricityConsumerAsset extends ElectricityAsset<ElectricityConsumerAsset> {@@ -41,11 +37,11 @@ public class ElectricityConsumerAsset extends ElectricityAsset<ElectricityConsumpublic static final AttributeDescriptor<Double> ENERGY_EXPORT_TOTAL = ElectricityAsset.ENERGY_EXPORT_TOTAL.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_IMPORT = ElectricityAsset.EFFICIENCY_IMPORT.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_EXPORT = ElectricityAsset.EFFICIENCY_EXPORT.withOptional(true);- public static final AttributeDescriptor<Double> TARIFF_IMPORT = ElectricityAsset.TARIFF_IMPORT.withOptional(true);- public static final AttributeDescriptor<Double> TARIFF_EXPORT = ElectricityAsset.TARIFF_EXPORT.withOptional(true);- public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricityAsset.CARBON_IMPORT.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricityAsset.CARBON_IMPORT_TOTAL.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricityAsset.CARBON_EXPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Double> TARIFF_IMPORT = ElectricitySupplierAsset.TARIFF_IMPORT.withOptional(true);+ public static final AttributeDescriptor<Double> TARIFF_EXPORT = ElectricitySupplierAsset.TARIFF_EXPORT.withOptional(true);+ public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricitySupplierAsset.CARBON_IMPORT.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricitySupplierAsset.CARBON_IMPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricitySupplierAsset.CARBON_EXPORT_TOTAL.withOptional(true);/*** For use by hydrators (i.e. JPA/Jackson)diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.javaindex 8ff25b9c0..74f5419c8 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.java@@ -34,11 +34,11 @@ public class ElectricityProducerAsset extends ElectricityAsset<ElectricityProducpublic static final AttributeDescriptor<Double> ENERGY_IMPORT_TOTAL = ElectricityAsset.ENERGY_IMPORT_TOTAL.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_IMPORT = ElectricityAsset.EFFICIENCY_IMPORT.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_EXPORT = ElectricityAsset.EFFICIENCY_EXPORT.withOptional(true);- public static final AttributeDescriptor<Double> TARIFF_IMPORT = ElectricityAsset.TARIFF_IMPORT.withOptional(true);- public static final AttributeDescriptor<Double> TARIFF_EXPORT = ElectricityAsset.TARIFF_EXPORT.withOptional(true);- public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricityAsset.CARBON_IMPORT.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricityAsset.CARBON_IMPORT_TOTAL.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricityAsset.CARBON_EXPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Double> TARIFF_IMPORT = ElectricitySupplierAsset.TARIFF_IMPORT.withOptional(true);+ public static final AttributeDescriptor<Double> TARIFF_EXPORT = ElectricitySupplierAsset.TARIFF_EXPORT.withOptional(true);+ public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricitySupplierAsset.CARBON_IMPORT.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricitySupplierAsset.CARBON_IMPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricitySupplierAsset.CARBON_EXPORT_TOTAL.withOptional(true);public static final AssetDescriptor<ElectricityProducerAsset> DESCRIPTOR = new AssetDescriptor<>("flash", "EABB4D", ElectricityProducerAsset.class);diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerSolarAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerSolarAsset.javaindex 15a7912b2..68b50018a 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerSolarAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerSolarAsset.java@@ -149,42 +149,6 @@ public class ElectricityProducerSolarAsset extends ElectricityProducerAsset {return this;}- @Override- public ElectricityProducerSolarAsset setTariffImport(Double value) {- super.setTariffImport(value);- return this;- }-- @Override- public ElectricityProducerSolarAsset setTariffExport(Double value) {- super.setTariffExport(value);- return this;- }-- @Override- public ElectricityProducerSolarAsset setCarbonImport(Double value) {- super.setCarbonImport(value);- return this;- }-- @Override- public ElectricityProducerSolarAsset setCarbonExport(Double value) {- super.setCarbonExport(value);- return this;- }-- @Override- public ElectricityProducerSolarAsset setCarbonImportTotal(Integer value) {- super.setCarbonImportTotal(value);- return this;- }-- @Override- public ElectricityProducerSolarAsset setCarbonExportTotal(Integer value) {- super.setCarbonExportTotal(value);- return this;- }-@Overridepublic ElectricityProducerSolarAsset setId(String id) {super.setId(id);diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerWindAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerWindAsset.javaindex 4cfdb3e07..0970660ec 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerWindAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerWindAsset.java@@ -121,42 +121,6 @@ public class ElectricityProducerWindAsset extends ElectricityProducerAsset {return this;}- @Override- public ElectricityProducerWindAsset setTariffImport(Double value) {- super.setTariffImport(value);- return this;- }-- @Override- public ElectricityProducerWindAsset setTariffExport(Double value) {- super.setTariffExport(value);- return this;- }-- @Override- public ElectricityProducerWindAsset setCarbonImport(Double value) {- super.setCarbonImport(value);- return this;- }-- @Override- public ElectricityProducerWindAsset setCarbonExport(Double value) {- super.setCarbonExport(value);- return this;- }-- @Override- public ElectricityProducerWindAsset setCarbonImportTotal(Integer value) {- super.setCarbonImportTotal(value);- return this;- }-- @Override- public ElectricityProducerWindAsset setCarbonExportTotal(Integer value) {- super.setCarbonExportTotal(value);- return this;- }-@Overridepublic ElectricityProducerWindAsset setId(String id) {super.setId(id);diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityStorageAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityStorageAsset.javaindex c0c38a98f..a2a8a346c 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityStorageAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityStorageAsset.java@@ -51,9 +51,9 @@ public abstract class ElectricityStorageAsset extends ElectricityAsset<Electricipublic static final AttributeDescriptor<Double> POWER_IMPORT_MIN = ElectricityAsset.POWER_IMPORT_MIN.withOptional(true);public static final AttributeDescriptor<Double> POWER_EXPORT_MIN = ElectricityAsset.POWER_EXPORT_MIN.withOptional(true);- public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricityAsset.CARBON_IMPORT.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricityAsset.CARBON_IMPORT_TOTAL.withOptional(true);- public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricityAsset.CARBON_EXPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricitySupplierAsset.CARBON_IMPORT.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = ElectricitySupplierAsset.CARBON_IMPORT_TOTAL.withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = ElectricitySupplierAsset.CARBON_EXPORT_TOTAL.withOptional(true);/*** For use by hydrators (i.e. JPA/Jackson)diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricitySupplierAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricitySupplierAsset.javaindex 657969ba8..314b1147c 100644--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricitySupplierAsset.java+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricitySupplierAsset.java@@ -28,16 +28,15 @@ import org.openremote.model.value.ValueType;import javax.persistence.Entity;import java.util.Optional;-import static org.openremote.model.Constants.UNITS_GRAM;-import static org.openremote.model.Constants.UNITS_KILO;+import static org.openremote.model.Constants.*;@Entitypublic class ElectricitySupplierAsset extends ElectricityAsset<ElectricitySupplierAsset> {- public static final AttributeDescriptor<Double> ENERGY_IMPORT_COST = new AttributeDescriptor<>("energyImportCost", ValueType.POSITIVE_NUMBER,+ public static final AttributeDescriptor<Double> ENERGY_IMPORT_COST = new AttributeDescriptor<>("energyImportCost", ValueType.NUMBER,new MetaItem<>(MetaItemType.READ_ONLY, true)).withUnits("EUR");- public static final AttributeDescriptor<Double> ENERGY_EXPORT_INCOME = new AttributeDescriptor<>("energyExportIncome", ValueType.POSITIVE_NUMBER,+ public static final AttributeDescriptor<Double> ENERGY_EXPORT_COST = new AttributeDescriptor<>("energyExportCost", ValueType.NUMBER,new MetaItem<>(MetaItemType.READ_ONLY, true)).withUnits("EUR");public static final AttributeDescriptor<Double> FINANCIAL_WALLET = new AttributeDescriptor<>("financialWallet", ValueType.NUMBER).withUnits("EUR");@@ -51,8 +50,19 @@ public class ElectricitySupplierAsset extends ElectricityAsset<ElectricitySupplipublic static final AttributeDescriptor<Double> POWER_EXPORT_MIN = ElectricityAsset.POWER_EXPORT_MIN.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_IMPORT = ElectricityAsset.EFFICIENCY_IMPORT.withOptional(true);public static final AttributeDescriptor<Integer> EFFICIENCY_EXPORT = ElectricityAsset.EFFICIENCY_EXPORT.withOptional(true);+ public static final AttributeDescriptor<Double> TARIFF_IMPORT = ElectricityAsset.TARIFF_IMPORT.withOptional(false);public static final AssetDescriptor<ElectricitySupplierAsset> DESCRIPTOR = new AssetDescriptor<>("upload-network", "9257A9", ElectricitySupplierAsset.class);+ public static final AttributeDescriptor<Double> CARBON_IMPORT = new AttributeDescriptor<>("carbonImport", ValueType.NUMBER)+ .withUnits(UNITS_KILO, UNITS_GRAM, UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR).withOptional(true);+ public static final AttributeDescriptor<Double> CARBON_EXPORT = new AttributeDescriptor<>("carbonExport", ValueType.NUMBER)+ .withUnits(UNITS_KILO, UNITS_GRAM, UNITS_PER, UNITS_KILO, UNITS_WATT, UNITS_HOUR).withOptional(true);+ public static final AttributeDescriptor<Integer> CARBON_IMPORT_TOTAL = new AttributeDescriptor<>("carbonImportTotal", ValueType.POSITIVE_INTEGER,+ new MetaItem<>(MetaItemType.READ_ONLY, true)+ ).withUnits(UNITS_KILO, UNITS_GRAM);+ public static final AttributeDescriptor<Integer> CARBON_EXPORT_TOTAL = new AttributeDescriptor<>("carbonExportTotal", ValueType.POSITIVE_INTEGER,+ new MetaItem<>(MetaItemType.READ_ONLY, true)+ ).withUnits(UNITS_KILO, UNITS_GRAM);/*** For use by hydrators (i.e. JPA/Jackson)@@ -68,15 +78,71 @@ public class ElectricitySupplierAsset extends ElectricityAsset<ElectricitySupplireturn getAttributes().getValue(ENERGY_IMPORT_COST);}- public Optional<Double> getEnergyExportIncome() {- return getAttributes().getValue(ENERGY_EXPORT_INCOME);+ public ElectricitySupplierAsset setEnergyImportCost(Double value) {+ getAttributes().getOrCreate(ENERGY_IMPORT_COST).setValue(value);+ return this;+ }++ public Optional<Double> getEnergyExportCost() {+ return getAttributes().getValue(ENERGY_EXPORT_COST);+ }++ public ElectricitySupplierAsset setEnergyExportCost(Double value) {+ getAttributes().getOrCreate(ENERGY_EXPORT_COST).setValue(value);+ return this;}public Optional<Double> getFinancialWallet() {return getAttributes().getValue(FINANCIAL_WALLET);}+ public ElectricitySupplierAsset setFinancialWallet(Double value) {+ getAttributes().getOrCreate(FINANCIAL_WALLET).setValue(value);+ return this;+ }+public Optional<Integer> getCarbonWallet() {return getAttributes().getValue(CARBON_WALLET);}++ public ElectricitySupplierAsset setCarbonWallet(Integer value) {+ getAttributes().getOrCreate(CARBON_WALLET).setValue(value);+ return this;+ }++ public Optional<Double> getCarbonImport() {+ return getAttributes().getValue(CARBON_IMPORT);+ }++ public ElectricitySupplierAsset setCarbonImport(Double value) {+ getAttributes().getOrCreate(CARBON_IMPORT).setValue(value);+ return this;+ }++ public Optional<Double> getCarbonExport() {+ return getAttributes().getValue(CARBON_EXPORT);+ }++ public ElectricitySupplierAsset setCarbonExport(Double value) {+ getAttributes().getOrCreate(CARBON_EXPORT).setValue(value);+ return this;+ }++ public Optional<Integer> getCarbonImportTotal() {+ return getAttributes().getValue(CARBON_IMPORT_TOTAL);+ }++ public ElectricitySupplierAsset setCarbonImportTotal(Integer value) {+ getAttributes().getOrCreate(CARBON_IMPORT_TOTAL).setValue(value);+ return this;+ }++ public Optional<Integer> getCarbonExportTotal() {+ return getAttributes().getValue(CARBON_EXPORT_TOTAL);+ }++ public ElectricitySupplierAsset setCarbonExportTotal(Integer value) {+ getAttributes().getOrCreate(CARBON_EXPORT_TOTAL).setValue(value);+ return this;+ }}diff --git a/model/src/main/java/org/openremote/model/asset/impl/EnergyOptimisationAsset.java b/model/src/main/java/org/openremote/model/asset/impl/EnergyOptimisationAsset.javanew file mode 100644index 000000000..eadf16e45--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/impl/EnergyOptimisationAsset.java@@ -0,0 +1,81 @@+/*+ * Copyright 2021, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.asset.impl;++import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetDescriptor;+import org.openremote.model.value.*;++import javax.persistence.Entity;++import java.util.Optional;++import static org.openremote.model.Constants.UNITS_PERCENTAGE;+import static org.openremote.model.value.ValueType.BOOLEAN;+import static org.openremote.model.value.ValueType.POSITIVE_NUMBER;++@Entity+public class EnergyOptimisationAsset extends Asset<EnergyOptimisationAsset> {++ public static final AttributeDescriptor<Integer> FINANCIAL_WEIGHTING = new AttributeDescriptor<>("financialWeighting", ValueType.POSITIVE_INTEGER)+ .withUnits(UNITS_PERCENTAGE).withConstraints(new ValueConstraint.Min(0), new ValueConstraint.Max(100))+ .withOptional(false);+ public static final AttributeDescriptor<Double> INTERVAL_SIZE = new AttributeDescriptor<>("intervalSize", POSITIVE_NUMBER);+ public static final AttributeDescriptor<Boolean> OPTIMISATION_DISABLED = new AttributeDescriptor<>("optimisationDisabled", BOOLEAN);++ public static final AssetDescriptor<EnergyOptimisationAsset> DESCRIPTOR = new AssetDescriptor<>("flash", "C4DB0D", EnergyOptimisationAsset.class);++ /**+ * For use by hydrators (i.e. JPA/Jackson)+ */+ protected EnergyOptimisationAsset() {+ }++ public EnergyOptimisationAsset(String name) {+ super(name);+ }++ public Optional<Integer> getFinancialWeighting() {+ return getAttribute(FINANCIAL_WEIGHTING).flatMap(AbstractNameValueHolder::getValue);+ }++ public EnergyOptimisationAsset setFinancialWeighting(Integer value) {+ getAttributes().getOrCreate(FINANCIAL_WEIGHTING).setValue(value);+ return this;+ }++ public Optional<Double> getIntervalSize() {+ return getAttribute(INTERVAL_SIZE).flatMap(AbstractNameValueHolder::getValue);+ }++ public EnergyOptimisationAsset setIntervalSize(Double value) {+ getAttributes().getOrCreate(INTERVAL_SIZE).setValue(value);+ return this;+ }++ public Optional<Boolean> isOptimisationDisabled() {+ return getAttribute(OPTIMISATION_DISABLED).flatMap(AbstractNameValueHolder::getValue);+ }++ public EnergyOptimisationAsset setOptimisationDisabled(Boolean value) {+ getAttributes().getOrCreate(OPTIMISATION_DISABLED).setValue(value);+ return this;+ }+}diff --git a/test/src/main/groovy/org/openremote/test/setup/KeycloakTestSetup.java b/test/src/main/groovy/org/openremote/test/setup/KeycloakTestSetup.javaindex f852e9295..ad5a75ca7 100644--- a/test/src/main/groovy/org/openremote/test/setup/KeycloakTestSetup.java+++ b/test/src/main/groovy/org/openremote/test/setup/KeycloakTestSetup.java@@ -58,6 +58,7 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {public String buildingUserId;public Tenant masterTenant;public Tenant tenantBuilding;+ public Tenant energyTenant;public Tenant tenantCity;public KeycloakTestSetup(Container container) {@@ -72,6 +73,7 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {masterTenant = identityService.getIdentityProvider().getTenant(Constants.MASTER_REALM);tenantBuilding = createTenant("building", "Building");tenantCity = createTenant("smartcity", "Smart City");+ energyTenant = createTenant("energy", "Energy Test");// Don't allow demo users to write assetsClientRole[] demoUserRoles = Arrays.stream(REGULAR_USER_ROLES)@@ -100,24 +102,22 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {this.smartCityUserId = smartCityUser.getId();keycloakProvider.updateUserRoles(tenantCity.getRealm(), smartCityUserId, "account"); // Remove all roles for account client- if (container.isDevMode()) {- /*- * MQTT Client- */- ClientRepresentation mqttClient = new ClientRepresentation();- String buildingMqttClientId = MqttBrokerService.MQTT_CLIENT_ID_PREFIX + UniqueIdentifierGenerator.generateId(tenantBuilding.getRealm());- mqttClient.setClientId(buildingMqttClientId);- mqttClient.setName("MQTT");- mqttClient.setStandardFlowEnabled(false);- mqttClient.setImplicitFlowEnabled(false);- mqttClient.setDirectAccessGrantsEnabled(false);- mqttClient.setServiceAccountsEnabled(true);- mqttClient.setSecret(UniqueIdentifierGenerator.generateId(tenantBuilding.getRealm()));- mqttClient = keycloakProvider.createClient(tenantBuilding.getRealm(), mqttClient);+ /*+ * MQTT Client+ */+ ClientRepresentation mqttClient = new ClientRepresentation();+ String buildingMqttClientId = MqttBrokerService.MQTT_CLIENT_ID_PREFIX + UniqueIdentifierGenerator.generateId(tenantBuilding.getRealm());+ mqttClient.setClientId(buildingMqttClientId);+ mqttClient.setName("MQTT");+ mqttClient.setStandardFlowEnabled(false);+ mqttClient.setImplicitFlowEnabled(false);+ mqttClient.setDirectAccessGrantsEnabled(false);+ mqttClient.setServiceAccountsEnabled(true);+ mqttClient.setSecret(UniqueIdentifierGenerator.generateId(tenantBuilding.getRealm()));+ mqttClient = keycloakProvider.createClient(tenantBuilding.getRealm(), mqttClient);- // Add asset RW roles to service user- User serviceUser = keycloakProvider.getClientServiceUser(tenantBuilding.getRealm(), mqttClient.getClientId());- keycloakProvider.updateUserRoles(tenantBuilding.getRealm(), serviceUser.getId(), KEYCLOAK_CLIENT_ID, ClientRole.READ_ASSETS.getValue(), ClientRole.WRITE_ASSETS.getValue(), ClientRole.WRITE_ATTRIBUTES.getValue());- }+ // Add asset RW roles to service user+ User serviceUser = keycloakProvider.getClientServiceUser(tenantBuilding.getRealm(), mqttClient.getClientId());+ keycloakProvider.updateUserRoles(tenantBuilding.getRealm(), serviceUser.getId(), KEYCLOAK_CLIENT_ID, ClientRole.READ_ASSETS.getValue(), ClientRole.WRITE_ASSETS.getValue(), ClientRole.WRITE_ATTRIBUTES.getValue());}}diff --git a/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.java b/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.javaindex 47a4d7951..ba51f425c 100644--- a/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.java+++ b/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.java@@ -117,7 +117,7 @@ public class ManagerTestSetup extends ManagerSetup {this.realmBuildingTenant = tenantBuilding.getRealm();this.realmCityTenant = tenantCity.getRealm();- // ################################ Demo assets for 'master' realm ###################################+ // ################################ Assets for 'master' realm ###################################BuildingAsset smartOffice = new BuildingAsset("Smart office");smartOffice.setRealm(masterRealm);@@ -204,7 +204,41 @@ public class ManagerTestSetup extends ManagerSetup {thing = assetStorageService.merge(thing);thingId = thing.getId();- // ################################ Demo assets for 'building' realm ###################################+ // ################################ Assets for 'energy' realm ###################################++ EnergyOptimisationAsset electricityOptimisationAsset = new EnergyOptimisationAsset("Optimisation");+ electricityOptimisationAsset.setIntervalSize(3d);+ electricityOptimisationAsset.setRealm(keycloakTestSetup.energyTenant.getRealm());+ electricityOptimisationAsset.setFinancialWeighting(100);+ electricityOptimisationAsset = assetStorageService.merge(electricityOptimisationAsset);++ ElectricityConsumerAsset electricityConsumerAsset = new ElectricityConsumerAsset("Consumer");+ electricityConsumerAsset.setParent(electricityOptimisationAsset);+ electricityConsumerAsset = assetStorageService.merge(electricityConsumerAsset);++ ElectricityProducerSolarAsset electricitySolarAsset = new ElectricityProducerSolarAsset("Producer");+ electricitySolarAsset.setParent(electricityOptimisationAsset);+ electricitySolarAsset = assetStorageService.merge(electricitySolarAsset);++ ElectricityBatteryAsset electricityBatteryAsset = new ElectricityBatteryAsset("Battery");+ electricityBatteryAsset.setParent(electricityOptimisationAsset);+ electricityBatteryAsset.setEnergyCapacity(100d);+ electricityBatteryAsset.setPowerImportMax(25d);+ electricityBatteryAsset.setPowerExportMax(25d);+ electricityBatteryAsset.setEfficiencyImport(95);+ electricityBatteryAsset.setEfficiencyExport(98);+ electricityBatteryAsset.setSupportsExport(true);+ electricityBatteryAsset.setSupportsImport(true);+ electricityBatteryAsset = assetStorageService.merge(electricityBatteryAsset);++ ElectricitySupplierAsset electricitySupplierAsset = new ElectricitySupplierAsset("Supplier");+ electricitySupplierAsset.setParent(electricityOptimisationAsset);+ electricitySupplierAsset.setTariffExport(-0.05);+ electricitySupplierAsset.setTariffImport(0.08);+ electricitySupplierAsset = assetStorageService.merge(electricitySupplierAsset);+++ // ################################ Assets for 'building' realm ###################################BuildingAsset smartBuilding = new BuildingAsset("Smart building");smartBuilding.setRealm(this.realmBuildingTenant);@@ -479,7 +513,7 @@ public class ManagerTestSetup extends ManagerSetup {apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);apartment3LivingroomId = apartment3Livingroom.getId();- // ################################ Link demo users and assets ###################################+ // ################################ Link users and assets ###################################assetStorageService.storeUserAsset(new UserAsset(keycloakTestSetup.tenantBuilding.getRealm(),keycloakTestSetup.testuser3Id,diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex e890e4474..bb1647d8b 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -242,7 +242,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "result should match (all assets in the master realm as user is not restricted)"assets.length == 5- assets.find {it.id == managerTestSetup.smartOfficeId}.attributes.size() == 8+ assets.find {it.id == managerTestSetup.smartOfficeId}.attributes.size() == 7// Assets should not be completely loaded (no path or parent info)assets.find {it.id == managerTestSetup.smartOfficeId}.path == nullassets.find {it.id == managerTestSetup.smartOfficeId}.parentId == null@@ -408,7 +408,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "result should match (all assets in the building realm as user is not restricted)"assets.length == 13- assets.find {it.id == managerTestSetup.smartBuildingId}.attributes.size() == 8+ assets.find {it.id == managerTestSetup.smartBuildingId}.attributes.size() == 7// Assets should not be completely loaded (no path or parent info)assets.find {it.id == managerTestSetup.smartBuildingId}.path == nullassets.find {it.id == managerTestSetup.smartBuildingId}.parentId == nulldiff --git a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovyindex f8de53534..6513d461b 100644--- a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy+++ b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy@@ -1,8 +1,23 @@package org.openremote.test.energy+import com.google.common.collect.Lists+import org.openremote.manager.agent.AgentService+import org.openremote.manager.asset.AssetProcessingService+import org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.datapoint.AssetDatapointService+import org.openremote.manager.energy.EnergyOptimisationService+import org.openremote.manager.energy.EnergyOptimiser+import org.openremote.manager.mqtt.MqttBrokerService+import org.openremote.manager.setup.SetupService+import org.openremote.model.attribute.AttributeEventimport org.openremote.test.ContainerTraitimport org.openremote.test.ManagerContainerTrait+import org.openremote.test.setup.ManagerTestSetup+import spock.lang.Ignoreimport spock.lang.Specification+import spock.util.concurrent.PollingConditions++import static org.openremote.manager.datapoint.AssetDatapointService.DATA_POINTS_MAX_AGE_DAYS_DEFAULT/** Copyright 2021, OpenRemote Inc.@@ -24,9 +39,27 @@ import spock.lang.Specification* along with this program. If not, see <http://www.gnu.org/licenses/>.*/+@Ignoreclass EnergyOptimisationAssetTest extends Specification implements ManagerContainerTrait {def "Test storage asset with consumer and producer"() {- when: "a storage asset is added"+ given: "the container environment is started"+ def spyOptimisationService = Spy(EnergyOptimisationService) {+ scheduleOptimisation(_ as String, _ as EnergyOptimiser) >> {+ optimisationAssetId, optimiser ->+ }++ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def services = Lists.newArrayList(defaultServices())+ services.replaceAll { it instanceof EnergyOptimisationService ? spyOptimisationService : it }+ def container = startContainer(defaultConfig(), services)+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)+ def agentService = container.getService(AgentService.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def assetDatapointService = container.getService(AssetDatapointService.class)++ when: "a storage asset is added"+ }}}diff --git a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationTest.groovy b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationTest.groovyindex 712e865b5..267e2466b 100644--- a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationTest.groovy+++ b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationTest.groovy@@ -2,7 +2,7 @@ package org.openremote.test.energyimport org.openremote.container.util.UniqueIdentifierGeneratorimport org.openremote.manager.energy.EnergyOptimiser-import org.openremote.model.asset.impl.ElectricityAsset+import org.openremote.model.asset.impl.ElectricitySupplierAssetimport org.openremote.model.attribute.AttributeRefimport org.openremote.model.util.Pairimport spock.lang.Specification@@ -48,18 +48,7 @@ class EnergyOptimisationTest extends Specification {def "Check basic import optimiser"() {given: "an energy optimisation instance"- def predictedProvider = {- AttributeRef attributeRef ->-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_IMPORT.name) {- return Collections.rotate(tariffImports.collect(), currentInterval)- }-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_EXPORT.name) {- return Collections.rotate(tariffExports.collect(), currentInterval)- }- }- def optimisation = new EnergyOptimiser(intervalSize, 1d, predictedProvider, { -> System.currentTimeMillis()})+ def optimisation = new EnergyOptimiser(intervalSize, 1d)and: "some import parameters"def powerImportMax = 7d@@ -148,18 +137,7 @@ class EnergyOptimisationTest extends Specification {given: "an energy optimisation instance"currentInterval = 0- def predictedProvider = {- AttributeRef attributeRef ->-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_IMPORT.name) {- return Collections.rotate(tariffImports.collect(), currentInterval)- }-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_EXPORT.name) {- return Collections.rotate(tariffExports.collect(), currentInterval)- }- }- def optimisation = new EnergyOptimiser(intervalSize, 1d, predictedProvider, { -> System.currentTimeMillis()})+ def optimisation = new EnergyOptimiser(intervalSize, 1d)and: "some storage export parameters"def powerExportMax = -20d@@ -211,18 +189,7 @@ class EnergyOptimisationTest extends Specification {given: "an energy optimisation instance"currentInterval = 0def currentTime = Instant.ofEpochMilli(System.currentTimeMillis()).atZone(ZoneId.systemDefault()).toLocalDate().atTime(23, 00).toEpochSecond(ZoneOffset.UTC) * 1000- def predictedProvider = {- AttributeRef attributeRef ->-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_IMPORT.name) {- return Collections.rotate(tariffImports.collect(), currentInterval)- }-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_EXPORT.name) {- return Collections.rotate(tariffExports.collect(), currentInterval)- }- }- def optimisation = new EnergyOptimiser(intervalSize, 1d, predictedProvider, { -> System.currentTimeMillis()})+ def optimisation = new EnergyOptimiser(intervalSize, 1d)and: "some input parameters"double energyCapacity = 200d@@ -274,7 +241,7 @@ class EnergyOptimisationTest extends Specification {when: "the optimisation is changed to have an interval size less than 1 hour"energyMinLevels = new double[24*4]- optimisation = new EnergyOptimiser(0.25d, 1d, predictedProvider, { -> System.currentTimeMillis()})+ optimisation = new EnergyOptimiser(0.25d, 1d)optimisation.applyEnergySchedule(energyMinLevels, energyCapacity, energyLevelMin, energyLevelMax, energyScheduleWeek, currentTime)then: "the energy min levels should be correct"@@ -287,18 +254,7 @@ class EnergyOptimisationTest extends Specification {given: "an energy optimisation instance"currentInterval = 0def currentTime = Instant.ofEpochMilli(System.currentTimeMillis()).atZone(ZoneId.systemDefault()).toLocalDate().atTime(23, 00).toEpochSecond(ZoneOffset.UTC) * 1000- def predictedProvider = {- AttributeRef attributeRef ->-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_IMPORT.name) {- return Collections.rotate(tariffImports.collect(), currentInterval)- }-- if (attributeRef.id == gridId && attributeRef.name == ElectricityAsset.TARIFF_EXPORT.name) {- return Collections.rotate(tariffExports.collect(), currentInterval)- }- }- def optimisation = new EnergyOptimiser(intervalSize, 1d, predictedProvider, { -> System.currentTimeMillis()})+ def optimisation = new EnergyOptimiser(intervalSize, 1d)and: "some input parameters"double energyCapacity = 200ddiff --git a/ui/util/webpack.util.js b/ui/util/webpack.util.jsindex 4147a16e9..1356144da 100644--- a/ui/util/webpack.util.js+++ b/ui/util/webpack.util.js@@ -151,16 +151,16 @@ function getAppConfig(mode, isDevServer, dirname, managerUrl, keycloakUrl) {}));- config.devtool = production ? false :"inline-source-map",- config.devServer = {- historyApiFallback: {- index: "/" + dirname.split(path.sep).slice(-1)[0] + "/",- },- port: 9000,- publicPath: "/" + dirname.split(path.sep).slice(-1)[0] + "/",- contentBase: OUTPUT_PATH,- disableHostCheck: true- };+ config.devtool = production ? false : "inline-source-map";+ config.devServer = {+ historyApiFallback: {+ index: "/" + dirname.split(path.sep).slice(-1)[0] + "/",+ },+ port: 9000,+ publicPath: "/" + dirname.split(path.sep).slice(-1)[0] + "/",+ contentBase: OUTPUT_PATH,+ disableHostCheck: true+ };config.watchOptions = {ignored: ['**/*.ts', 'node_modules']}