How about something like:
For the time period of interest, add up all the Off times, add up all the On
times, and subtract the sum of the On from the sum of the Off.
If the answer is negative, add the duration of the time period.
I think the result will be the duration of time the state was On.
Example:
During one day (24 hours), suppose the state changes are:
08:00 On
09:30 Off
13:15 On
19:45 Off
Total on time = 1:30 + 6:30 = 8:00
Sum of Off times = 09:30 + 19:45 = 29:15
Sum of On times = 08:00 + 13:15 = 21:15
Sum(Off) - Sum(On) = 29:15 - 21:15 = 8:00
If there was no On state change at 08:00 (so it had already been on since
midnight):
Total on time = 9:30 + 6:30 = 16:00
Sum of Off times = 29:15
Sum of On times = 13:15
Sum(Off) - Sum(On) = 29:15 - 13:15 = 16:00
Alternatively, if the 08:00 On time was still there, but it didn’t turn off at
19:45 and instead remained on until midnight:
Total on time = 1:30 + 10:45 = 12:15
Sum of Off times = 09:30
Sum of On times = 21:15
Sum(Off) - Sum(On) = 09:30 - 21:15 = -11:45
This is negative, so add the duration (24 hours) = 12:15
Regards,
Antony.