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
Energy optimisation and storage updates (chargers ignored if vehicle connected, forceCharge attribute added)
Rich Turnerbfa8c36fa1ef
diff --git a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.javaindex 04ffbdfe4..2fdab47f2 100644--- a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java+++ b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java@@ -32,10 +32,10 @@ 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.AssetFilter;import org.openremote.model.asset.impl.*;import org.openremote.model.attribute.Attribute;import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.ValueDatapoint;@@ -102,6 +102,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Containerprotected GatewayService gatewayService;protected ScheduledExecutorService executorService;protected Map<String, OptimisationInstance> assetOptimisationInstanceMap = new HashMap<>();+ protected List<String> forceChargeAssetIds = new ArrayList<>();@Overridepublic int getPriority() {@@ -143,8 +144,8 @@ public class EnergyOptimisationService extends RouteBuilder implements ContainerclientEventService.addInternalSubscription(AttributeEvent.class,- new AssetFilter<>(energyOptimisationAssets.stream().map(Asset::getId).toArray(String[]::new)),- this::processAttributeChange);+ null,+ this::processAttributeEvent);}@SuppressWarnings("unchecked")@@ -174,14 +175,40 @@ public class EnergyOptimisationService extends RouteBuilder implements Container}}- protected void processAttributeChange(AttributeEvent attributeEvent) {-+ protected void processAttributeEvent(AttributeEvent attributeEvent) {OptimisationInstance optimisationInstance = assetOptimisationInstanceMap.get(attributeEvent.getAssetId());- if (optimisationInstance == null) {+ if (optimisationInstance != null) {+ processOptimisationAssetAttributeEvent(optimisationInstance, attributeEvent);+ return;+ }++ String attributeName = attributeEvent.getAttributeName();++ if ((attributeName.equals(ElectricityChargerAsset.VEHICLE_CONNECTED.getName()) || attributeName.equals(ElectricVehicleAsset.CHARGER_CONNECTED.getName()))+ && attributeEvent.<Boolean>getValue().orElse(false)) {+ // Look for forced charge asset+ if (forceChargeAssetIds.remove(attributeEvent.getAssetId())) {+ LOG.fine("Previously force charged asset has now been removed: " + attributeEvent.getAssetId());+ }return;}+ // Check for request to force charge+ if (attributeName.equals(ElectricityStorageAsset.FORCE_CHARGE.getName()) && attributeEvent.<AttributeExecuteStatus>getValue().orElse(null) == AttributeExecuteStatus.REQUEST_START) {+ Asset<?> storageAsset = assetStorageService.find(attributeEvent.getAssetId());+ if (storageAsset instanceof ElectricityStorageAsset) {+ forceChargeAssetIds.add(attributeEvent.getAssetId());+ double powerImportMax = ((ElectricityStorageAsset) storageAsset).getPowerImportMax().orElse(Double.MAX_VALUE);+ LOG.fine("Request to force charge asset '" + attributeEvent.getAssetId() + "': attempting to set powerSetpoint=" + powerImportMax);+ assetProcessingService.sendAttributeEvent(new AttributeEvent(storageAsset.getId(), ElectricityAsset.POWER_SETPOINT, powerImportMax));+ assetProcessingService.sendAttributeEvent(new AttributeEvent(storageAsset.getId(), ElectricityStorageAsset.FORCE_CHARGE, AttributeExecuteStatus.COMPLETED));+ }+ }+ }++ protected void processOptimisationAssetAttributeEvent(OptimisationInstance optimisationInstance, AttributeEvent attributeEvent) {+if (EnergyOptimisationAsset.FINANCIAL_SAVING.getName().equals(attributeEvent.getAttributeName())|| EnergyOptimisationAsset.CARBON_SAVING.getName().equals(attributeEvent.getAttributeName())) {// These are updated by this service@@ -319,6 +346,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Containerreturn;}+ double[] powerNets = new double[intervalCount];ElectricitySupplierAsset supplierAsset = supplierAssets.get(0);if (LOG.isLoggable(Level.FINEST)) {@@ -332,24 +360,71 @@ public class EnergyOptimisationService extends RouteBuilder implements ContainerLOG.finest(getLogPrefix(optimisationAssetId) + "Fetching optimisable child assets of type '" + ElectricityStorageAsset.class.getSimpleName() + "'");- AssetQuery query = new AssetQuery()- .select(new AssetQuery.Select().excludePath(true))- .recursive(true)- .parents(optimisationAssetId)- .types(ElectricityStorageAsset.class)- .attributes(- new LogicGroup<>(- LogicGroup.Operator.AND,- Collections.singletonList(new LogicGroup<>(- LogicGroup.Operator.OR,- new AttributePredicate(ElectricityStorageAsset.SUPPORTS_IMPORT.getName(), new BooleanPredicate(true)),- new AttributePredicate(ElectricityStorageAsset.SUPPORTS_EXPORT.getName(), new BooleanPredicate(true))- )),- new AttributePredicate().name(new StringPredicate(ElectricityAsset.POWER_SETPOINT.getName())))- );-- List<ElectricityStorageAsset> optimisableStorageAssets = assetStorageService.findAll(query).stream()+ List<ElectricityStorageAsset> optimisableStorageAssets = assetStorageService.findAll(+ new AssetQuery()+ .select(new AssetQuery.Select().excludePath(true).excludeParentInfo(true))+ .recursive(true)+ .parents(optimisationAssetId)+ .types(ElectricityStorageAsset.class)+ .attributes(+ new LogicGroup<>(+ LogicGroup.Operator.AND,+ Collections.singletonList(new LogicGroup<>(+ LogicGroup.Operator.OR,+ new AttributePredicate(ElectricityStorageAsset.SUPPORTS_IMPORT.getName(), new BooleanPredicate(true)),+ new AttributePredicate(ElectricityStorageAsset.SUPPORTS_EXPORT.getName(), new BooleanPredicate(true))+ )),+ new AttributePredicate().name(new StringPredicate(ElectricityAsset.POWER_SETPOINT.getName())))+ )+ )+ .stream().map(asset -> (ElectricityStorageAsset)asset)+ .collect(Collectors.toList());++ List<ElectricityStorageAsset> finalOptimisableStorageAssets = optimisableStorageAssets;+ optimisableStorageAssets = optimisableStorageAssets+ .stream()+ .filter(asset -> {++ // Exclude force charged assets (so we don't mess with the setpoint)+ if (forceChargeAssetIds.contains(asset.getId())) {+ LOG.finest("Optimisable asset was requested to force charge so it won't be optimised: " + asset.getId());+ @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]);+ return false;+ }++ if (asset instanceof ElectricityChargerAsset) {+ // Check if it has a child vehicle asset+ return finalOptimisableStorageAssets.stream()+ .noneMatch(a -> {+ if (a.getParentId().equals(asset.getId())) {+ // Take the lowest power max from vehicle or charger+ double vehiclePowerImportMax = a.getPowerImportMax().orElse(Double.MAX_VALUE);+ double vehiclePowerExportMax = a.getPowerExportMax().orElse(Double.MAX_VALUE);+ double chargerPowerImportMax = asset.getPowerImportMax().orElse(Double.MAX_VALUE);+ double chargerPowerExportMax = asset.getPowerExportMax().orElse(Double.MAX_VALUE);+ double smallestPowerImportMax = Math.min(vehiclePowerImportMax, chargerPowerImportMax);+ double smallestPowerExportMax = Math.min(vehiclePowerExportMax, chargerPowerExportMax);++ if (smallestPowerImportMax < vehiclePowerImportMax) {+ LOG.fine("Reducing vehicle power import max due to connected charger limit: vehicle=" + a.getId() + ", oldPowerImportMax=" + vehiclePowerImportMax + ", newPowerImportMax=" + smallestPowerImportMax);+ a.setPowerImportMax(smallestPowerImportMax);+ }+ if (smallestPowerExportMax < vehiclePowerExportMax) {+ LOG.fine("Reducing vehicle power Export max due to connected charger limit: vehicle=" + a.getId() + ", oldPowerExportMax=" + vehiclePowerExportMax + ", newPowerExportMax=" + smallestPowerExportMax);+ a.setPowerExportMax(smallestPowerExportMax);+ }+ LOG.finest("Excluding charger from optimisable assets and child vehicle will be used instead: " + asset.getId());+ return true;+ }+ return false;+ });+ }+ return true;+ }).sorted(Comparator.comparingInt(asset -> asset.getEnergyLevelSchedule().map(schedule -> 0).orElse(1))).collect(Collectors.toList());@@ -362,9 +437,6 @@ public class EnergyOptimisationService extends RouteBuilder implements ContainerLOG.finest(getLogPrefix(optimisationAssetId) + "Found optimisable child assets of type '" + ElectricityStorageAsset.class.getSimpleName() + "': " + optimisableStorageAssets.stream().map(Asset::getId).collect(Collectors.joining(", ")));}- // Get consumers and producers and sum power demand for the next 24hrs- double[] powerNets = new double[intervalCount];-LOG.finest(getLogPrefix(optimisationAssetId) + "Fetching plain consumer and producer child assets of type '" + ElectricityProducerAsset.class.getSimpleName() + "', '" + ElectricityConsumerAsset.class.getSimpleName() + "', '" + ElectricityStorageAsset.class.getSimpleName() + "'");AtomicInteger count = new AtomicInteger(0);@@ -385,7 +457,9 @@ public class EnergyOptimisationService extends RouteBuilder implements ContainerIntStream.range(0, intervalCount).forEach(i -> powerNets[i] += powerLevels[i]);count.incrementAndGet();});- assetStorageService.findAll(++ // Get power of storage assets that don't support neither import or export (treat them as plain consumers/producers)+ List<ElectricityStorageAsset> plainStorageAssets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().excludePath(true).excludeParentInfo(true)).recursive(true)@@ -396,13 +470,42 @@ public class EnergyOptimisationService extends RouteBuilder implements Containernew AttributePredicate(ElectricityStorageAsset.SUPPORTS_IMPORT.getName(), new BooleanPredicate(true), true, null),new AttributePredicate(ElectricityStorageAsset.SUPPORTS_EXPORT.getName(), new BooleanPredicate(true), true, null))- ).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]);- count.incrementAndGet();- });+ )+ .stream()+ .map(asset -> (ElectricityStorageAsset)asset)+ .collect(Collectors.toList());++ // Exclude chargers with a power value != 0 and a child vehicle with a power value != 0 (avoid double counting - vehicle takes priority)+ plainStorageAssets+ .stream()+ .filter(asset -> {+ if (asset instanceof ElectricityChargerAsset) {+ // Check if it has a child vehicle asset also check optimisable assets as child vehicle could be in there+ return plainStorageAssets.stream()+ .noneMatch(a -> {+ if (a.getParentId().equals(asset.getId())) {+ LOG.finest("Excluding charger from plain consumer/producer calculations to avoid double counting power: " + asset.getId());+ return true;+ }+ return false;+ }) && finalOptimisableStorageAssets.stream()+ .noneMatch(a -> {+ if (a.getParentId().equals(asset.getId())) {+ LOG.finest("Excluding charger from plain consumer/producer calculations to avoid double counting power: " + asset.getId());+ return true;+ }+ return false;+ });+ }+ return true;+ })+ .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]);+ count.incrementAndGet();+ });if (LOG.isLoggable(Level.FINER)) {LOG.finer(getLogPrefix(optimisationAssetId) + "Found plain consumer and producer child assets count=" + count.get());@@ -503,7 +606,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Container}double maxEnergyLevelMin = Arrays.stream(energyLevelMins).max().orElse(0);- boolean isConnected = !(storageAsset instanceof ElectricVehicleAsset) || ((ElectricVehicleAsset)storageAsset).getChargerConnected().orElse(false);+ boolean isConnected = storageAssetConnected(storageAsset);// TODO: Make these a function of energy levelFunction<Integer, Double> powerImportMaxCalculator = interval -> interval == 0 && !isConnected ? 0 : powerImportMax;@@ -526,6 +629,12 @@ public class EnergyOptimisationService extends RouteBuilder implements Containerfor (int i = 0; i < powerNets.length; i++) {if (i == 0) {+ if (!storageAssetConnected(storageAsset)) {+ LOG.finer("Optimised storage asset not connected so interval 0 will not be counted or actioned: " + storageAsset.getId());+ setpoints[i] = 0;+ continue;+ }+// Update savings/cost data with costs specific to this assetif (setpoints[i] > 0) {financialCost += storageAsset.getTariffImport().orElse(0d) * setpoints[i] * intervalSize;@@ -556,7 +665,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Container}// Clear out un-optimised data for not found assets- optimisationInstance.unoptimisedStorageAssetEnergyLevels.keySet().removeAll(obsoleteUnoptimisedAssetIds);+ obsoleteUnoptimisedAssetIds.forEach(optimisationInstance.unoptimisedStorageAssetEnergyLevels.keySet()::remove);// Calculate and store savings datacarbonCost = (powerNets[0] >= 0 ? supplierAsset.getCarbonImport().orElse(0d) : -1 * supplierAsset.getCarbonExport().orElse(0d)) * powerNets[0] * intervalSize;@@ -685,7 +794,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Containerdouble energyLevel = Math.min(energyCapacity, storageAsset.getEnergyLevel().orElse(-1d));double powerExportMax = storageAsset.getPowerExportMax().map(power -> -1*power).orElse(Double.MIN_VALUE);double powerImportMax = storageAsset.getPowerImportMax().orElse(Double.MAX_VALUE);- boolean isConnected = !(storageAsset instanceof ElectricVehicleAsset) || ((ElectricVehicleAsset)storageAsset).getChargerConnected().orElse(false);+ boolean isConnected = storageAssetConnected(storageAsset);// TODO: Make these a function of energy levelFunction<Integer, Double> powerImportMaxCalculator = interval -> interval == 0 && !isConnected ? 0 : powerImportMax;@@ -737,13 +846,23 @@ public class EnergyOptimisationService extends RouteBuilder implements Containerreturn powerSetpoints;}+ protected boolean storageAssetConnected(ElectricityStorageAsset storageAsset) {+ if (storageAsset instanceof ElectricVehicleAsset) {+ return ((ElectricVehicleAsset)storageAsset).getChargerConnected().orElse(false);+ }+ if (storageAsset instanceof ElectricityChargerAsset) {+ return ((ElectricityChargerAsset)storageAsset).getVehicleConnected().orElse(false);+ }+ return true;+ }+/*** Gets the un-optimised import power for the first (current) interval for the supplied storage asset*/protected double getStorageUnoptimisedImportPower(OptimisationInstance optimisationInstance, String optimisationAssetId, ElectricityStorageAsset storageAsset, double energyLevelTarget, double remainingPowerCapacity) {double intervalSize = optimisationInstance.energyOptimiser.getIntervalSize();- boolean isConnected = !(storageAsset instanceof ElectricVehicleAsset) || ((ElectricVehicleAsset)storageAsset).getChargerConnected().orElse(false);+ boolean isConnected = storageAssetConnected(storageAsset);if (!isConnected) {optimisationInstance.unoptimisedStorageAssetEnergyLevels.remove(storageAsset.getId());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 b081d132a..73b2d38a6 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@@ -19,6 +19,7 @@*/package org.openremote.model.asset.impl;+import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.attribute.MetaItem;import org.openremote.model.value.AttributeDescriptor;import org.openremote.model.value.MetaItemType;@@ -48,6 +49,7 @@ public abstract class ElectricityStorageAsset extends ElectricityAsset<Electrici.withUnits(UNITS_PERCENTAGE).withConstraints(new ValueConstraint.Min(0), new ValueConstraint.Max(100));public static final AttributeDescriptor<Integer[][]> ENERGY_LEVEL_SCHEDULE = new AttributeDescriptor<>("energyLevelSchedule", ValueType.POSITIVE_INTEGER.asArray().asArray()).withOptional(true);+ public static final AttributeDescriptor<AttributeExecuteStatus> FORCE_CHARGE = new AttributeDescriptor<>("forceCharge", ValueType.EXECUTION_STATUS);public static final AttributeDescriptor<Double> POWER_SETPOINT = ElectricityAsset.POWER_SETPOINT.withOptional(false);public static final AttributeDescriptor<Double> POWER_IMPORT_MIN = ElectricityAsset.POWER_IMPORT_MIN.withOptional(true);diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.java b/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.javaindex 57568cfef..68d40d3a2 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.java@@ -51,22 +51,7 @@ public enum AttributeExecuteStatus {/*** Execution is currently running*/- RUNNING(false),-- /**- * Execution was cancelled- */- CANCELLED(false),-- /**- * Command produced an error- */- ERROR(false),-- /**- * Execution has been disabled- */- DISABLED(false);+ RUNNING(false);private boolean write;// Prevents cloning of values each time fromString is called