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 WIP
Rich Turnerfc90bb77b1bc
diff --git a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.javaindex 65f01b979..2c240cf88 100644--- a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java+++ b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java@@ -168,7 +168,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Containerprotected void stopOptimisation(String optimisationAssetId) {Pair<EnergyOptimiser, ScheduledFuture<?>> optimiserAndScheduler = assetEnergyOptimiserMap.remove(optimisationAssetId);- if (optimiserAndScheduler == null) {+ if (optimiserAndScheduler == null || optimiserAndScheduler.value == null) {return;}@@ -214,12 +214,14 @@ public class EnergyOptimisationService extends RouteBuilder implements ContainerTimeUnit.SECONDS);}+ /**+ * Gets the start time of the current interval+ */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);+ Instant optimisationStartTime = now+ .truncatedTo(ChronoUnit.DAYS);while (optimisationStartTime.isBefore(now)) {optimisationStartTime = optimisationStartTime.plus(periodSeconds, ChronoUnit.SECONDS);diff --git a/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.java b/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.javaindex ba51f425c..f7b503ef3 100644--- a/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.java+++ b/test/src/main/groovy/org/openremote/test/setup/ManagerTestSetup.java@@ -99,6 +99,11 @@ public class ManagerTestSetup extends ManagerSetup {public String area1Id;public String microphone1Id;public String peopleCounter3AssetId;+ public String electricityOptimisationAssetId;+ public String electricityConsumerAssetId;+ public String electricitySolarAssetId;+ public String electricitySupplierAssetId;+ public String electricityBatteryAssetId;public ManagerTestSetup(Container container, boolean importDemoScenes) {super(container);@@ -205,20 +210,22 @@ public class ManagerTestSetup extends ManagerSetup {thingId = thing.getId();// ################################ Assets for 'energy' realm ###################################-EnergyOptimisationAsset electricityOptimisationAsset = new EnergyOptimisationAsset("Optimisation");electricityOptimisationAsset.setIntervalSize(3d);electricityOptimisationAsset.setRealm(keycloakTestSetup.energyTenant.getRealm());electricityOptimisationAsset.setFinancialWeighting(100);electricityOptimisationAsset = assetStorageService.merge(electricityOptimisationAsset);+ electricityOptimisationAssetId = electricityOptimisationAsset.getId();ElectricityConsumerAsset electricityConsumerAsset = new ElectricityConsumerAsset("Consumer");electricityConsumerAsset.setParent(electricityOptimisationAsset);electricityConsumerAsset = assetStorageService.merge(electricityConsumerAsset);+ electricityConsumerAssetId = electricityConsumerAsset.getId();ElectricityProducerSolarAsset electricitySolarAsset = new ElectricityProducerSolarAsset("Producer");electricitySolarAsset.setParent(electricityOptimisationAsset);electricitySolarAsset = assetStorageService.merge(electricitySolarAsset);+ electricitySolarAssetId = electricitySolarAsset.getId();ElectricityBatteryAsset electricityBatteryAsset = new ElectricityBatteryAsset("Battery");electricityBatteryAsset.setParent(electricityOptimisationAsset);@@ -230,13 +237,14 @@ public class ManagerTestSetup extends ManagerSetup {electricityBatteryAsset.setSupportsExport(true);electricityBatteryAsset.setSupportsImport(true);electricityBatteryAsset = assetStorageService.merge(electricityBatteryAsset);+ electricityBatteryAssetId = electricityBatteryAsset.getId();ElectricitySupplierAsset electricitySupplierAsset = new ElectricitySupplierAsset("Supplier");electricitySupplierAsset.setParent(electricityOptimisationAsset);electricitySupplierAsset.setTariffExport(-0.05);electricitySupplierAsset.setTariffImport(0.08);electricitySupplierAsset = assetStorageService.merge(electricitySupplierAsset);-+ electricitySupplierAssetId = electricitySupplierAsset.getId();// ################################ Assets for 'building' realm ###################################diff --git a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovyindex 6513d461b..583009698 100644--- a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy+++ b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy@@ -1,23 +1,29 @@package org.openremote.test.energyimport com.google.common.collect.Lists-import org.openremote.manager.agent.AgentService+import org.openremote.container.timer.TimerServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService-import org.openremote.manager.datapoint.AssetDatapointService+import org.openremote.manager.datapoint.AssetPredictedDatapointServiceimport org.openremote.manager.energy.EnergyOptimisationServiceimport org.openremote.manager.energy.EnergyOptimiser-import org.openremote.manager.mqtt.MqttBrokerServiceimport org.openremote.manager.setup.SetupService+import org.openremote.model.asset.impl.ElectricityAsset+import org.openremote.model.asset.impl.ElectricityStorageAssetimport org.openremote.model.attribute.AttributeEvent-import org.openremote.test.ContainerTrait+import org.openremote.model.attribute.AttributeRefimport org.openremote.test.ManagerContainerTraitimport org.openremote.test.setup.ManagerTestSetupimport spock.lang.Ignoreimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions-import static org.openremote.manager.datapoint.AssetDatapointService.DATA_POINTS_MAX_AGE_DAYS_DEFAULT+import java.time.Instant+import java.time.temporal.ChronoUnit+import java.util.concurrent.Executors++import static org.spockframework.util.Assert.that+import static spock.util.matcher.HamcrestMatchers.closeTo/** Copyright 2021, OpenRemote Inc.@@ -38,28 +44,89 @@ import static org.openremote.manager.datapoint.AssetDatapointService.DATA_POINTS* 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/>.*/-@Ignoreclass EnergyOptimisationAssetTest extends Specification implements ManagerContainerTrait {def "Test storage asset with consumer and producer"() {given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def scheduler = Executors.newScheduledThreadPool(1);+ def services = Lists.newArrayList(defaultServices())def spyOptimisationService = Spy(EnergyOptimisationService) {scheduleOptimisation(_ as String, _ as EnergyOptimiser) >> {- optimisationAssetId, optimiser ->+ // Don't use the scheduler as we will manually trigger the optimisation for testing+ optimisationAssetId, optimiser -> 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.assetEnergyOptimiserMap.isEmpty()+ assert optimisationService.assetEnergyOptimiserMap.get(managerTestSetup.electricityOptimisationAssetId) != null+ }++ and: "the optimisation start time should be correctly calculated"+ def optimiser = optimisationService.assetEnergyOptimiserMap.get(managerTestSetup.electricityOptimisationAssetId).key+ def now = Instant.ofEpochMilli(timerService.getCurrentTimeMillis())+ def optimisationTime = optimisationService.getOptimisationStartTime(now.toEpochMilli(), (long)optimiser.intervalSize * 60 * 60)+ assert optimisationTime.isBefore(now)+ assert optimisationTime.plus((long)optimiser.intervalSize*60, ChronoUnit.MINUTES).isAfter(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]+ now = Instant.ofEpochMilli(timerService.getCurrentTimeMillis()).truncatedTo(ChronoUnit.HOURS)+ 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), now.plus((long)(optimiser.intervalSize * 60)*(i-1), ChronoUnit.MINUTES).toEpochMilli())+ assetPredictedDatapointService.updateValue(new AttributeRef(managerTestSetup.electricitySupplierAssetId, ElectricityAsset.TARIFF_EXPORT.name), tariffExports.get(i), now.plus((long)(optimiser.intervalSize * 60)*(i-1), ChronoUnit.MINUTES).toEpochMilli())+ }++ and: "consumer and producer prediction values are set for the next 24hrs"+ [-5, -25, 15, 0, 0, -5, -5, -2]+ def consumerPower = [0, 5, 10, 0, 0, 10, 5, 0]+ def producerPower = [-5, -30, -5, 0, 0, -15, -10, -2]+ 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), tariffImports.get(i), now.plus((long)(optimiser.intervalSize * 60)*(i-1), ChronoUnit.MINUTES).toEpochMilli())+ assetPredictedDatapointService.updateValue(new AttributeRef(managerTestSetup.electricitySolarAssetId, ElectricityAsset.POWER.name), tariffExports.get(i), now.plus((long)(optimiser.intervalSize * 60)*(i-1), ChronoUnit.MINUTES).toEpochMilli())+ }++ and: "the optimisation runs"+ optimisationService.runOptimisation(managerTestSetup.electricityOptimisationAssetId, optimisationTime)- 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)+ then: "the setpoints of the storage asset for the next 24hrs should be correctly optimised"+ conditions.eventually {+ assert ((ElectricityStorageAsset)assetStorageService.find(managerTestSetup.electricityBatteryAssetId)).getPowerSetpoint().orElse(0d) == 7d+ def setpoints = assetPredictedDatapointService.getValueDatapoints(+ new AttributeRef(managerTestSetup.electricityBatteryAssetId, ElectricityAsset.POWER_SETPOINT.name),+ "minute",+ ((long)optimiser.intervalSize * 60) + " minute",+ timerService.currentTimeMillis,+ Instant.ofEpochMilli(timerService.currentTimeMillis).plus(1, ChronoUnit.DAYS).toEpochMilli()+ )- when: "a storage asset is added"+ assert setpoints.size() == 7+ assert setpoints[0].value == 7d+ assert setpoints[1].value == 7d+ assert that(setpoints[2].value, closeTo(2.33333, 0.0001))+ assert that(setpoints[3].value, closeTo(-4.66666, 0.0001))+ assert setpoints[4].value == 7d+ assert setpoints[5].value == -20d+ assert that(setpoints[6].value, closeTo(-5.66666, 0.0001))}}}