Use drools to find the percentage change in average temperature over an hour

799 Views Asked by At

I have a use case where I have a stream of room temperatures coming up. The stream has reading of temperature for every minute. I want to calculate the average temperature per hour and raise an alarm if the average temperature for this hour exceeds the average temperature for the last hour by 5 degrees.

For Example: I have readings from 1:00 pm to 2:00 pm...I calculate the average temperature for this hour. Lets say its A. I have readings from 2:00 pm to 3:00 pm.. I calculate the average temperature for this hour. Lets say its B. I needs to raise alarm if B-A >=5

I am unable to come up with DRL file for this. Can anyone help me on this.

1

There are 1 best solutions below

0
On

Is this supposed to work in a sliding manner or actually hour by hour? I'm assuming the first, but it shouldn't be too difficult to adapt for the second case. The solution is based on two auxiliary objects of class Average one of subclass OldAverage and the other one of subclass NewAverage, to be inserted up front. The first two rules are for the build-up during the first two hours.

rule "during first hour"
when
    $avg: OldAverage( size < 60 )
    $r: Reading()
then
    modify( $avg ){ addReading( $r ) }  // add $r to List<Reading>
    retract ( $r );
end

rule "during second hour"
when
    $old: OldAverage( size == 60 )
    $new: NewAverage( size < 60 )
    $r: Reading()
then
    modify( $new ){ addReading( $r ) }
    retract ( $r );
end

From now on, a Reading pushed out from the NewAverage object must be added to the OldAverage object.

rule "after two hours"
when
    $old: OldAverage( size == 60 )
    $new: NewAverage( size == 60 )
    $r: Reading()
then
    Reading r = $new.addReading( $r );  // addReading returns List.remove(0)
    modify( $old ){ addReading( r ) }
    update( $new );
    retract ( $r );
end

And here's the rule to check:

rule "check for increase"
when
    $old: OldAverage( size == 60, $oldAvg: average )
    $new: NewAverage( size == 60, average > $oldAvg + 5 )
then
    System.out.println( "average temperature increased by more than 5 degrees" );
end