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
Bug fix for Energy Optimisation savings calculation and added test
Rich Turner37f5b37aa085
diff --git a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.javaindex 8cf7189f1..68bf70f22 100644--- a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java+++ b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java@@ -476,6 +476,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Containeroptimiser.applyEnergySchedule(energyLevelMins, energyLevelMaxs, energyCapacity, energySchedule, LocalDateTime.ofInstant(Instant.ofEpochMilli(timerService.getCurrentTimeMillis()), ZoneId.systemDefault()));}+ double maxEnergyLevelMin = Arrays.stream(energyLevelMins).max().orElse(0);boolean isConnected = !(storageAsset instanceof ElectricVehicleAsset) || ((ElectricVehicleAsset)storageAsset).getChargerConnected().orElse(false);// TODO: Make these a function of energy level@@ -520,7 +521,6 @@ public class EnergyOptimisationService extends RouteBuilder implements Container// Update unoptimised power for this assetobsoleteUnoptimisedAssetIds.remove(storageAsset.getId());- double maxEnergyLevelMin = Arrays.stream(energyLevelMins).max().orElse(0);double assetUnoptimisedPower = getStorageUnoptimisedImportPower(optimisationInstance, optimisationAssetId, storageAsset, maxEnergyLevelMin, Math.max(0, powerImportMax - unoptimisedPower));unoptimisedPower += assetUnoptimisedPower;unoptimisedFinancialCost += storageAsset.getTariffImport().orElse(0d) * assetUnoptimisedPower * intervalSize;@@ -533,7 +533,7 @@ public class EnergyOptimisationService extends RouteBuilder implements ContainercarbonCost = (powerNets[0] >= 0 ? supplierAsset.getCarbonImport().orElse(0d) : supplierAsset.getCarbonExport().orElse(0d)) * powerNets[0] * intervalSize;financialCost += (powerNets[0] >= 0 ? supplierAsset.getTariffImport().orElse(0d) : supplierAsset.getTariffExport().orElse(0d)) * powerNets[0] * intervalSize;unoptimisedCarbonCost = (unoptimisedPower >= 0 ? supplierAsset.getCarbonImport().orElse(0d) : supplierAsset.getCarbonExport().orElse(0d)) * unoptimisedPower * intervalSize;- unoptimisedFinancialCost += (unoptimisedPower >= 0 ? supplierAsset.getTariffImport().orElse(0d) : supplierAsset.getTariffExport().orElse(0d)) * unoptimisedPower * intervalSize;+ unoptimisedFinancialCost += (unoptimisedPower >= 0 ? supplierAsset.getTariffImport().orElse(0d) : -1 * supplierAsset.getTariffExport().orElse(0d)) * unoptimisedPower * intervalSize;double financialSaving = unoptimisedFinancialCost - financialCost;double carbonSaving = unoptimisedCarbonCost - carbonCost;@@ -705,24 +705,6 @@ public class EnergyOptimisationService extends RouteBuilder implements ContainerLOG.finer(getLogPrefix(optimisationAssetId) + "Calculated earning opportunity power set points for storage asset: " + storageAsset.getId() + " = " + Arrays.toString(powerSetpoints));}- if (LOG.isLoggable(Level.FINEST)) {-- double previousCost = 0d;- double optimisedCost = 0d;-- for (int i = 0; i < powerSetpoints.length; i++) {- double power = powerNets[i];- previousCost += Math.abs(power) * (power > 0 ? costImports[i] : costExports[i]) * optimiser.intervalSize;- power += powerSetpoints[i];- optimisedCost += Math.abs(power) * (power > 0 ? costImports[i] : costExports[i]) * optimiser.intervalSize;- optimisedCost += Math.abs(power) * (power > 0 ? storageAsset.getTariffImport().orElse(0d) : storageAsset.getTariffExport().orElse(0d)) * optimiser.intervalSize;- }-- // TODO Include storage import/export tariff-- LOG.finest(getLogPrefix(optimisationAssetId) + "Optimisation result for storage asset: " + storageAsset.getId() + " [Previous cost=" + previousCost + ", new cost=" + optimisedCost + "]");- }-return powerSetpoints;}diff --git a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovyindex 8d848c27b..df807d855 100644--- a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy+++ b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy@@ -12,6 +12,7 @@ import org.openremote.model.asset.impl.*import org.openremote.model.attribute.AttributeEventimport org.openremote.model.attribute.AttributeRefimport org.openremote.model.datapoint.DatapointInterval+import org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTraitimport org.openremote.test.setup.ManagerTestSetupimport spock.lang.Specification@@ -24,6 +25,8 @@ import java.time.ZoneIdimport java.time.temporal.ChronoUnitimport java.util.concurrent.TimeUnit+import static spock.util.matcher.HamcrestMatchers.closeTo+/** Copyright 2021, OpenRemote Inc.*@@ -81,13 +84,13 @@ class EnergyOptimisationAssetTest extends Specification implements ManagerContaithen: "the optimisation start time should be correctly calculated"def optimiser = optimisationService.assetOptimisationInstanceMap.get(managerTestSetup.electricityOptimisationAssetId).energyOptimiserdef optimisationTime = optimisationService.getOptimisationStartTime(now.toEpochMilli(), (long)optimiser.intervalSize * 60 * 60)+ def optimisationDateTime = LocalDateTime.ofInstant(optimisationTime, ZoneId.systemDefault())assert optimisationTime.isBefore(now)assert optimisationTime.plus((long)optimiser.intervalSize*60, ChronoUnit.MINUTES).equals(now)when: "supplier tariff values are set for the next 24hrs"def tariffExports = [-5, -2, -8, 2, 2, 5, -2, -2]def tariffImports = [3, -5, 10, 1, 3, -5, 7, 8]- def optimisationDateTime = LocalDateTime.ofInstant(optimisationTime, ZoneId.systemDefault())assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricitySupplierAssetId, ElectricityAsset.TARIFF_IMPORT.name, tariffImports.get(0)))assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricitySupplierAssetId, ElectricityAsset.TARIFF_EXPORT.name, tariffExports.get(0)))@@ -195,4 +198,170 @@ class EnergyOptimisationAssetTest extends Specification implements ManagerContaiassert setpoints[6].value == 0d}}++ def "Test savings calculations"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def services = Lists.newArrayList(defaultServices())+ def spyOptimisationService = Spy(EnergyOptimisationService) {+ scheduleOptimisation(_ as String, _ as EnergyOptimiser, _ as Duration, _ as Long) >> {+ // Don't use the scheduler as we will manually trigger the optimisation for testing+ optimisationAssetId, optimiser, startDuration, periodSeconds ->+ return null+ }+ }++ services.replaceAll { it instanceof EnergyOptimisationService ? spyOptimisationService : it }+ def container = startContainer(defaultConfig(), services)+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)+ def optimisationService = container.getService(EnergyOptimisationService.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def assetPredictedDatapointService = container.getService(AssetPredictedDatapointService.class)+ def timerService = container.getService(TimerService.class)++ expect: "an optimisation instance should exist"+ conditions.eventually {+ assert !optimisationService.assetOptimisationInstanceMap.isEmpty()+ assert optimisationService.assetOptimisationInstanceMap.get(managerTestSetup.electricityOptimisationAssetId) != null+ }++ when: "the battery energy level is set to lower limit for ease of testing"+ def batteryAsset = assetStorageService.find(managerTestSetup.electricityBatteryAssetId) as ElectricityBatteryAsset+ batteryAsset.setEnergyLevel(40)+ batteryAsset.setPowerImportMax(10)+ batteryAsset.setPowerExportMax(10)+ batteryAsset = assetStorageService.merge(batteryAsset)++ and: "the pseudo clock is stopped and the system time is set to midnight of two days time"+ stopPseudoClock()+ def now = Instant.ofEpochMilli(timerService.getCurrentTimeMillis())+ now = now.truncatedTo(ChronoUnit.DAYS).plus(2, ChronoUnit.DAYS)+ advancePseudoClock(now.toEpochMilli()-timerService.getCurrentTimeMillis(), TimeUnit.MILLISECONDS, container)++ then: "the optimisation start time should be correctly calculated"+ def optimiser = optimisationService.assetOptimisationInstanceMap.get(managerTestSetup.electricityOptimisationAssetId).energyOptimiser+ def optimisationTime = optimisationService.getOptimisationStartTime(now.toEpochMilli(), (long)optimiser.intervalSize * 60 * 60)+ def optimisationDateTime = LocalDateTime.ofInstant(optimisationTime, ZoneId.systemDefault())+ assert optimisationTime.isBefore(now)+ assert optimisationTime.plus((long)optimiser.intervalSize*60, ChronoUnit.MINUTES).equals(now)++ and: "consumer and producer prediction values are set for the next 24hrs"+ def consumerPower = [0, 0, 0, 0, 10, 10, 10, 10]+ def producerPower = [-10, -10, -10, -10, 0, 0, 0, 0]+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricityConsumerAssetId, ElectricityAsset.POWER.name, consumerPower.get(0)))+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricitySolarAssetId, ElectricityAsset.POWER.name, producerPower.get(0)))++ for (int i = 1; i < consumerPower.size(); i++) {+ assetPredictedDatapointService.updateValue(new AttributeRef(managerTestSetup.electricityConsumerAssetId, ElectricityAsset.POWER.name), consumerPower.get(i), optimisationDateTime.plus((long)(optimiser.intervalSize * 60)*i, ChronoUnit.MINUTES))+ assetPredictedDatapointService.updateValue(new AttributeRef(managerTestSetup.electricitySolarAssetId, ElectricityAsset.POWER.name), producerPower.get(i), optimisationDateTime.plus((long)(optimiser.intervalSize * 60)*i, ChronoUnit.MINUTES))+ }++ and: "supplier tariff values are set for the next 24hrs"+ def tariffExports = [-0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05]+ def tariffImports = [0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08]+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricitySupplierAssetId, ElectricityAsset.TARIFF_IMPORT.name, tariffImports.get(0)))+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricitySupplierAssetId, ElectricityAsset.TARIFF_EXPORT.name, tariffExports.get(0)))++ for (int i = 1; i < tariffExports.size(); i++) {+ assetPredictedDatapointService.updateValue(new AttributeRef(managerTestSetup.electricitySupplierAssetId, ElectricityAsset.TARIFF_IMPORT.name), tariffImports.get(i), optimisationDateTime.plus((long)(optimiser.intervalSize * 60)*i, ChronoUnit.MINUTES))+ assetPredictedDatapointService.updateValue(new AttributeRef(managerTestSetup.electricitySupplierAssetId, ElectricityAsset.TARIFF_EXPORT.name), tariffExports.get(i), optimisationDateTime.plus((long)(optimiser.intervalSize * 60)*i, ChronoUnit.MINUTES))+ }++ then: "the current values of each attribute should have reached the DB"+ conditions.eventually {+ assert (assetStorageService.find(managerTestSetup.electricityConsumerAssetId) as ElectricityConsumerAsset).getPower().orElse(-1d) == consumerPower.get(0)+ assert (assetStorageService.find(managerTestSetup.electricitySolarAssetId) as ElectricityProducerSolarAsset).getPower().orElse(-1d) == producerPower.get(0)+ }++ when: "the optimisation asset is reset which will cause optimisation to run"+ def optimisationAsset = assetStorageService.find(managerTestSetup.electricityOptimisationAssetId) as EnergyOptimisationAsset+ optimisationAsset.setOptimisationDisabled(true)+ optimisationAsset.setFinancialSaving(0d)+ optimisationAsset = Values.clone(assetStorageService.merge(optimisationAsset))+ optimisationAsset.setOptimisationDisabled(false)+ optimisationAsset = assetStorageService.merge(optimisationAsset)++ then: "the battery setpoint should be set to max (7kW) to store produced energy for future deficit"+ conditions.eventually {+ assert ((ElectricityStorageAsset)assetStorageService.find(managerTestSetup.electricityBatteryAssetId)).getPowerSetpoint().orElse(0d) == 10d++ def setpoints = assetPredictedDatapointService.getValueDatapoints(+ new AttributeRef(managerTestSetup.electricityBatteryAssetId, ElectricityAsset.POWER_SETPOINT.name),+ DatapointInterval.MINUTE,+ (int)(optimiser.intervalSize * 60),+ LocalDateTime.ofInstant(optimisationTime, ZoneId.systemDefault()).plus((long)(optimiser.intervalSize * 60), ChronoUnit.MINUTES),+ LocalDateTime.ofInstant(optimisationTime, ZoneId.systemDefault()).plus(1, ChronoUnit.DAYS).minus((long)(optimiser.intervalSize * 60), ChronoUnit.MINUTES)+ )++ assert setpoints.size() == 7+ assert setpoints[0].value == 10d+ assert setpoints[1].value == 10d+ assert setpoints[2].value == 10d+ assert setpoints[3].value == -10d+ assert setpoints[4].value == -10d+ assert setpoints[5].value == -10d+ assert setpoints[6].value == -10d+ }++ and: "the optimisation saving should be inverse of earning from lost production export -(10x3x0.05)"+ conditions.eventually {+ assert (assetStorageService.find(managerTestSetup.electricityOptimisationAssetId) as EnergyOptimisationAsset).getFinancialSaving().orElse(0d) == -1.5+ }++ when: "another optimisation run occurs"+ batteryAsset.setEnergyLevel(70d)+ batteryAsset = assetStorageService.merge(batteryAsset)+ optimisationService.runOptimisation(managerTestSetup.electricityOptimisationAssetId, optimisationTime.plus((long)optimiser.intervalSize*60, ChronoUnit.MINUTES))++ then: "the optimisation saving should have decreased by the same amount (i.e. cost)"+ conditions.eventually {+ assert ((ElectricityStorageAsset)assetStorageService.find(managerTestSetup.electricityBatteryAssetId)).getPowerSetpoint().orElse(0d) == 10d+ assert (assetStorageService.find(managerTestSetup.electricityOptimisationAssetId) as EnergyOptimisationAsset).getFinancialSaving().orElse(0d) == -3.0+ }++ when: "another optimisation run occurs"+ batteryAsset.setEnergyLevel(100d)+ batteryAsset = assetStorageService.merge(batteryAsset)+ optimisationService.runOptimisation(managerTestSetup.electricityOptimisationAssetId, optimisationTime.plus((long)optimiser.intervalSize*60*2, ChronoUnit.MINUTES))++ then: "the optimisation saving should have decreased by the same amount (i.e. cost)"+ conditions.eventually {+ assert ((ElectricityStorageAsset)assetStorageService.find(managerTestSetup.electricityBatteryAssetId)).getPowerSetpoint().orElse(0d) == 10d+ assert (assetStorageService.find(managerTestSetup.electricityOptimisationAssetId) as EnergyOptimisationAsset).getFinancialSaving().orElse(0d) == -4.5+ }++ when: "another optimisation run occurs"+ batteryAsset.setEnergyLevel(130d)+ batteryAsset = assetStorageService.merge(batteryAsset)+ optimisationService.runOptimisation(managerTestSetup.electricityOptimisationAssetId, optimisationTime.plus((long)optimiser.intervalSize*60*3, ChronoUnit.MINUTES))++ then: "the optimisation saving should have decreased by the same amount (i.e. cost)"+ conditions.eventually {+ assert ((ElectricityStorageAsset)assetStorageService.find(managerTestSetup.electricityBatteryAssetId)).getPowerSetpoint().orElse(0d) == 10d+ assert (assetStorageService.find(managerTestSetup.electricityOptimisationAssetId) as EnergyOptimisationAsset).getFinancialSaving().orElse(0d) == -6.0+ }++ when: "the consumer and producer power attributes are updated (as they have changed according to the predicted data)"+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricityConsumerAssetId, ElectricityAsset.POWER.name, consumerPower.get(4)))+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.electricitySolarAssetId, ElectricityAsset.POWER.name, producerPower.get(4)))++ then: "the values should have reached the DB"+ conditions.eventually {+ assert (assetStorageService.find(managerTestSetup.electricityConsumerAssetId) as ElectricityConsumerAsset).getPower().orElse(-1d) == consumerPower.get(4)+ assert (assetStorageService.find(managerTestSetup.electricitySolarAssetId) as ElectricityProducerSolarAsset).getPower().orElse(-1d) == producerPower.get(4)+ }++ when: "another optimisation run occurs (this should now be exporting from storage)"+ batteryAsset.setEnergyLevel(160d)+ batteryAsset = assetStorageService.merge(batteryAsset)+ optimisationService.runOptimisation(managerTestSetup.electricityOptimisationAssetId, optimisationTime.plus((long)optimiser.intervalSize*60*4, ChronoUnit.MINUTES))++ then: "the optimisation saving should have increased by the cost to import 30kWh (as battery will now be exporting)"+ conditions.eventually {+ assert ((ElectricityStorageAsset)assetStorageService.find(managerTestSetup.electricityBatteryAssetId)).getPowerSetpoint().orElse(0d) == -10d+ assert (assetStorageService.find(managerTestSetup.electricityOptimisationAssetId) as EnergyOptimisationAsset).getFinancialSaving().orElse(0d), closeTo(-6.0+2.4, 0.1)+ }+ }}