Search code examples
javadroolscomplex-event-processingdrools-fusion

Drools Fusion rule language: pedometer rule


I'm a newbie to Drools (version 6.3) and I have some trouble coming up with a specific rule. I have a class called Steps with just a simple field double steps;. Each step event represent the steps taken since the previous event and I have a working rule that says that you need to get moving when you do not do 50 steps in the last hour:

declare Steps
    @role(event)
end

rule "STEPS RULE"
when
    $totalSteps : Number( doubleValue < 50 ) from accumulate(
        Steps( stepsCount : steps ) over window:time( 1h ) from entry-point     
    "entrySteps", sum( stepsCount ) )

then
    System.out.println("STEPS RULE: get moving!");
end

Now instead that each event is the steps taken since previous event, I want that they represent the cumulative steps. So if an event has 50 steps and you take 20 steps, then I want that the next event has 70 steps. The question is how can I change my rule so it would still work?


Solution

  • For a pedometer you'll need another class, distinct from Steps, your event class. The rules for updating your pedometer are simple.

    rule "create pedometer"
    when
        Steps( $s: steps )
        not Pedometer()
    then
        insert( new Pedometer( $s ) );
    end
    
    rule "update pedometer"
    no-loop
    when
        Steps( $s: steps )
        $p: Pedometer( $r: readout )
    then
        modify( $p ){
            setReadout( $r + $s )
        }
    end
    

    Edit If Steps already contains accumulated values, it's a little more complicated since you need to calculate the differences between the first and the last pedometer readings in the window.

    rule "ACC STEPS RULE"
    when
        accumulate( Steps( $s : steps )
                    over window:time( 1h ) from entry-point "entrySteps"; 
            $fst: min( $s ), $lst: max( $s );
            $lst - $fst < 50 )
    then
        System.out.println("STEPS RULE: get moving!");
    end
    

    There should be at least one reading per hour or another rule detecting this situation.