Search in sources :

Example 1 with RuleExecution

use of org.openhab.core.automation.RuleExecution in project openhab-core by openhab.

the class RuleExecutionSimulator method simulateExecutionsForCronBasedRule.

/**
 * Simulates all {@link RuleExecution} for the given cron expression of the given rule.
 *
 * @param rule {@link Rule} to be simulated.
 * @param from {@link ZonedDateTime} earliest time to be contained in the rule simulation.
 * @param until {@link ZonedDateTime} latest time to be contained in the rule simulation.
 * @param cron cron-expression to be evaluated for determining the execution times.
 * @return a list of expected executions.
 */
private List<RuleExecution> simulateExecutionsForCronBasedRule(Rule rule, ZonedDateTime from, ZonedDateTime until, SchedulerTemporalAdjuster temporalAdjuster) {
    final List<RuleExecution> result = new ArrayList<>();
    ZonedDateTime currentTime = ZonedDateTime.from(temporalAdjuster.adjustInto(from));
    while (!temporalAdjuster.isDone(currentTime) && currentTime.isBefore(until)) {
        // if the current time satisfies all conditions add the instance to the result
        if (checkConditions(rule, currentTime)) {
            result.add(new RuleExecution(Date.from(currentTime.toInstant()), rule));
        }
        currentTime = ZonedDateTime.from(temporalAdjuster.adjustInto(currentTime));
    }
    return result;
}
Also used : RuleExecution(org.openhab.core.automation.RuleExecution) ZonedDateTime(java.time.ZonedDateTime) ArrayList(java.util.ArrayList)

Example 2 with RuleExecution

use of org.openhab.core.automation.RuleExecution in project openhab-core by openhab.

the class RuleExecutionSimulator method simulateExecutionsForRule.

/**
 * Simulates the next executions for the given {@link Rule} until the given {@link Date}.
 *
 * @param rule {@link Rule} to be simulated.
 * @param from {@link ZonedDateTime} earliest time to be contained in the rule simulation.
 * @param until {@link ZonedDateTime} latest time to be contained in the rule simulation.
 * @return List of expected {@link RuleExecution}.
 */
private List<RuleExecution> simulateExecutionsForRule(Rule rule, ZonedDateTime from, ZonedDateTime until) {
    final List<RuleExecution> executions = new ArrayList<>();
    for (Trigger trigger : rule.getTriggers()) {
        TriggerHandler triggerHandler = (TriggerHandler) this.ruleEngine.getModuleHandler(trigger, rule.getUID());
        // Only triggers that are time-based will be considered within the simulation
        if (triggerHandler instanceof TimeBasedTriggerHandler) {
            SchedulerTemporalAdjuster temporalAdjuster = ((TimeBasedTriggerHandler) triggerHandler).getTemporalAdjuster();
            if (temporalAdjuster != null) {
                executions.addAll(simulateExecutionsForCronBasedRule(rule, from, until, temporalAdjuster));
            }
        }
    }
    logger.debug("Created {} rule simulations for rule {}.", executions.size(), rule.getName());
    return executions;
}
Also used : SchedulerTemporalAdjuster(org.openhab.core.scheduler.SchedulerTemporalAdjuster) Trigger(org.openhab.core.automation.Trigger) RuleExecution(org.openhab.core.automation.RuleExecution) TriggerHandler(org.openhab.core.automation.handler.TriggerHandler) TimeBasedTriggerHandler(org.openhab.core.automation.handler.TimeBasedTriggerHandler) ArrayList(java.util.ArrayList) TimeBasedTriggerHandler(org.openhab.core.automation.handler.TimeBasedTriggerHandler)

Example 3 with RuleExecution

use of org.openhab.core.automation.RuleExecution in project openhab-core by openhab.

the class RuleResource method simulateRules.

@GET
@Path("/schedule/simulations")
@Produces(MediaType.APPLICATION_JSON)
@Operation(operationId = "getScheduleRuleSimulations", summary = "Simulates the executions of rules filtered by tag 'Schedule' within the given times.", responses = { @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = RuleExecution.class)))), @ApiResponse(responseCode = "400", description = "The max. simulation duration of 180 days is exceeded.") })
public Response simulateRules(@Parameter(description = "Start time of the simulated rule executions. Will default to the current time. [" + DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS + "]") @QueryParam("from") @Nullable String from, @Parameter(description = "End time of the simulated rule executions. Will default to 30 days after the start time. Must be less than 180 days after the given start time. [" + DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS + "]") @QueryParam("until") @Nullable String until) {
    final ZonedDateTime fromDate = from == null || from.isEmpty() ? ZonedDateTime.now() : parseTime(from);
    final ZonedDateTime untilDate = until == null || until.isEmpty() ? fromDate.plusDays(31) : parseTime(until);
    if (daysBetween(fromDate, untilDate) >= 180) {
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Simulated time span must be smaller than 180 days.");
    }
    final Stream<RuleExecution> ruleExecutions = ruleManager.simulateRuleExecutions(fromDate, untilDate);
    return Response.ok(ruleExecutions.collect(Collectors.toList())).build();
}
Also used : RuleExecution(org.openhab.core.automation.RuleExecution) ZonedDateTime(java.time.ZonedDateTime) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Operation(io.swagger.v3.oas.annotations.Operation)

Example 4 with RuleExecution

use of org.openhab.core.automation.RuleExecution in project openhab-core by openhab.

the class RuleSimulationTest method testSimulateRuleWithCronTrigger.

@Test
public void testSimulateRuleWithCronTrigger() {
    logger.info("assert that rules are simulated correct");
    final Rule cronRuleWithTimeOfDayCondition = createRuleWithCronExpressionTrigger();
    final Rule disabledRule = createRuleWithCronExpressionTrigger();
    final Rule timeOfDayTriggerWithDayOfWeekCondition = createRuleWithTimeOfDayTrigger();
    final Rule timeOfDayTriggerWithEphemerisCondition = createRuleWithEphemerisCondition();
    RuleProvider ruleProvider = new RuleProvider() {

        @Override
        public void addProviderChangeListener(ProviderChangeListener<Rule> listener) {
        }

        @Override
        public Collection<Rule> getAll() {
            return Set.of(cronRuleWithTimeOfDayCondition, timeOfDayTriggerWithDayOfWeekCondition, timeOfDayTriggerWithEphemerisCondition, disabledRule);
        }

        @Override
        public void removeProviderChangeListener(ProviderChangeListener<Rule> listener) {
        }
    };
    // Register the RuleProvider, so that the rules are registered within the ruleRegistry.
    registerService(ruleProvider);
    assertThat(ruleRegistry.get(cronRuleWithTimeOfDayCondition.getUID()), is(notNullValue()));
    assertThat(ruleRegistry.get(disabledRule.getUID()), is(notNullValue()));
    assertThat(ruleRegistry.get(timeOfDayTriggerWithDayOfWeekCondition.getUID()), is(notNullValue()));
    assertThat(ruleRegistry.get(timeOfDayTriggerWithEphemerisCondition.getUID()), is(notNullValue()));
    // Disable one rule, so it must not be contained within the simulation
    ruleEngine.setEnabled(disabledRule.getUID(), false);
    assertFalse(ruleEngine.isEnabled(disabledRule.getUID()));
    // Simulate for two weeks
    final ZonedDateTime from = ZonedDateTime.of(2021, 1, 4, 0, 0, 0, 0, ZoneId.systemDefault());
    final ZonedDateTime until = ZonedDateTime.of(2021, 1, 17, 23, 59, 59, 0, ZoneId.systemDefault());
    List<RuleExecution> executions = ruleEngine.simulateRuleExecutions(from, until).collect(Collectors.toList());
    // Every rule fires twice a week. We simulate for two weeks so we expect 12 executions
    // TODO: must be 12, but Ephemeris Condition is not yet evaluated in test, because dayset is not configured.
    assertEquals(8, executions.size());
    Iterator<RuleExecution> it = executions.iterator();
    // due the result is sorted, check the results by position.
    // First week
    checkExecution(it.next(), timeOfDayTriggerWithDayOfWeekCondition, 4, 16, 00);
    checkExecution(it.next(), cronRuleWithTimeOfDayCondition, 6, 10, 30);
    checkExecution(it.next(), timeOfDayTriggerWithDayOfWeekCondition, 6, 16, 00);
    checkExecution(it.next(), cronRuleWithTimeOfDayCondition, 8, 10, 30);
    // checkExecution(it.next(), timeOfDayTriggerWithEphemerisCondition, 9, 10, 00);
    // checkExecution(it.next(), timeOfDayTriggerWithEphemerisCondition, 10, 10, 00);
    // Second week
    checkExecution(it.next(), timeOfDayTriggerWithDayOfWeekCondition, 11, 16, 00);
    checkExecution(it.next(), cronRuleWithTimeOfDayCondition, 13, 10, 30);
    checkExecution(it.next(), timeOfDayTriggerWithDayOfWeekCondition, 13, 16, 00);
    checkExecution(it.next(), cronRuleWithTimeOfDayCondition, 15, 10, 30);
    // checkExecution(it.next(), timeOfDayTriggerWithEphemerisCondition, 16, 10, 00);
    // checkExecution(it.next(), timeOfDayTriggerWithEphemerisCondition, 17, 10, 00);
    assertFalse(it.hasNext());
}
Also used : RuleExecution(org.openhab.core.automation.RuleExecution) ZonedDateTime(java.time.ZonedDateTime) ProviderChangeListener(org.openhab.core.common.registry.ProviderChangeListener) Rule(org.openhab.core.automation.Rule) RuleProvider(org.openhab.core.automation.RuleProvider) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Aggregations

RuleExecution (org.openhab.core.automation.RuleExecution)4 ZonedDateTime (java.time.ZonedDateTime)3 ArrayList (java.util.ArrayList)2 Operation (io.swagger.v3.oas.annotations.Operation)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 Test (org.junit.jupiter.api.Test)1 Rule (org.openhab.core.automation.Rule)1 RuleProvider (org.openhab.core.automation.RuleProvider)1 Trigger (org.openhab.core.automation.Trigger)1 TimeBasedTriggerHandler (org.openhab.core.automation.handler.TimeBasedTriggerHandler)1 TriggerHandler (org.openhab.core.automation.handler.TriggerHandler)1 ProviderChangeListener (org.openhab.core.common.registry.ProviderChangeListener)1 SchedulerTemporalAdjuster (org.openhab.core.scheduler.SchedulerTemporalAdjuster)1 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)1