Answer to Stackoverflow question asking to calculate time when some device is on during some time period:

Types:

package com.text;

import java.util.Deque;

declare EventA
    @role( event )
    id: int;
    on: boolean;
end

declare Session
    id: int @key;
    events: Deque;
end

declare Report
    id: int @key;
    timestamp: long @key;
    onInLast5Mins: int;
end

Rules:

package com.text;

import java.util.Deque;
import java.util.ArrayDeque;

declare enum Constants

    // 20 seconds - faster to test
    WINDOW_SIZE(20*1000);
    
    value: int;
end

global co.streamx.kie.api.runtime.Events events;

rule "Reporter"
    // 20 seconds - faster to test
    timer(cron:0/20 * * ? * * *)
when
    $s: Session()
then
    long now = System.currentTimeMillis();

    int on = 0; //how long was on
    int off = 0; //how long was off
    int toPersist = 0; //last interesting event
    
    for (EventA a : (Deque<EventA>)$s.getEvents()) {
        toPersist ++;
        boolean stop = false;
        // time elapsed since the reading till now
        int delta = (int)(now - events.getTimestamp(a, "events"));
        if (delta >= Constants.WINDOW_SIZE.getValue()) {
            delta = Constants.WINDOW_SIZE.getValue();
            stop = true;
        }
        
        // remove time already counted
        delta -= (on+off);
        if (a.isOn())
            on += delta;
        else
            off += delta;
            
        if (stop)
            break;
    }
    
    int toRemove = $s.getEvents().size() - toPersist;
    while (toRemove > 0) {
        // this event is out of window of interest - delete
        delete($s.getEvents().removeLast());
        toRemove --;
    }
    
    insertLogical(new Report($s.getId(), now, on));
end

rule "SessionCreate"
when
    // for every new EventA
    $a: EventA($id: id) from entry-point events
    // check there is no session
    not (exists(Session(id == $id)))
then
    insert(new Session($id, new ArrayDeque()));
end

rule "SessionJoin"
when
    // for every new EventA
    $a : EventA() from entry-point events
    // get event's session
    $g: Session(id == $a.id)
then
    $g.getEvents().push($a);
end