Duration of switch ON time in hour_minutes_seconds

In case anyone wants to do this same thing in Flux, there are a few ways that I know of:

If your machine or switch is always 0, 1, 0, 1, etc. then something like this:

from(bucket: "RetroEncabulator")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "BinaryData")
  |> filter(fn: (r) => r["_field"] == "value")
  |> elapsed(unit: 1s)
  |> map(fn: (r) => ({ r with elapsedFloat: float(v: r.elapsed)/3600.0 })) // convert seconds to hours
  |> filter(fn: (r) => r["_value"] == 0) // add a filter statement after the elapsed function to filter out only those whose _value = 0. This is because the “active” time (when the state 1 goes to state 0) is captured in those records where _value = 0. If you wanted to know the time when the phone is NOT active, you would set the filter where _value = 1.
  |> aggregateWindow(every: 1d, fn: sum, column:"elapsedFloat")
  |> yield(name: "sum")

If your machine or switch generates consecutive On or Off values (such as 1, 1, 0, 1, 0, 0, 1, 1, etc.), then something like this:

import "contrib/tomhollingworth/events"
from(bucket: "RetroEncabulator")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "BinaryData")
  |> filter(fn: (r) => r["_field"] == "value")
  |> events.duration(
    unit: 1s,
    columnName: "duration",
    timeColumn: "_time",
    stopColumn: "_stop",
    stop: 2023-01-01T00:00:00Z
)
  |> map(fn: (r) => ({ r with durationFloat: float(v: r.duration)/3600.0 }))
  |> filter(fn: (r) => r["_value"] == 1)
  |> aggregateWindow(every: 1d, fn: sum, column:"durationFloat")
  |> yield(name: "sum")

and if one wants a bar chart of hours of “on” time per day, something like this:

1 Like