The error message runtime error @12:6-12:57: filter: type conflict: time != int indicates a type mismatch when performing an operation. Although it points to line 12 (the elapsed function call), the actual problem arises later when r.delta_time (which is an integer representing nanoseconds) is subtracted from a time value (time_final) in the map function.
Flux requires that when subtracting from a time value, the subtrahend must be a duration type, not an int. The elapsed function correctly produces delta_time as an integer representing nanoseconds, but this integer needs to be explicitly converted to a duration before it can be used in time calculations.
The fix involves using the duration() function to convert r.delta_time to a duration before subtracting it from time_final.
Original problematic line:
time_initial = time_final - r.delta_time
Corrected line:
time_initial = time_final - duration(v: r.delta_time)
Here's the corrected Flux query:
import "math"
from(bucket: "${BUCKET}")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r["_measurement"] =~ /${DEVICE:regex}/)
|> filter(fn: (r) => r["_field"] == "BMS_FastUpdateSOC")
|> aggregateWindow(every: v.windowPeriod, fn: mean)
|> sort(columns: ["_time"])
|> duplicate(column: "_value", as: "current_soc")
|> elapsed(unit: 1ns, columnName: "delta_time")
|> difference(nonNegative: false, keepFirst: true, columns: ["current_soc"])
|> filter(fn: (r) => math.abs(x: r.current_soc) > 0.1)
|> map(fn: (r) => {
// After 'difference(columns: ["current_soc"])':
// r._value holds the original aggregated SOC (soc_final).
// r.current_soc holds the calculated SOC change.
// r.delta_time holds the time elapsed (in ns).
soc_change = r.current_soc // This is the difference in SOC
current_soc_final = r._value // This is the SOC at _time (final SOC)
previous_soc = current_soc_final - soc_change // Calculate initial SOC
// Calculate timestamps
time_final = r._time
// Convert delta_time (integer ns) to a duration for time arithmetic
time_initial = time_final - duration(v: r.delta_time)
return {
_time: r._time, // Final timestamp
time_initial: time_initial, // Initial timestamp
time_final: time_final, // Final timestamp
delta_time: r.delta_time, // Duration in nanoseconds
soc_initial: math.round(x: previous_soc * 10.0) / 10.0,
soc_final: math.round(x: current_soc_final * 10.0) / 10.0,
soc_change: math.round(x: soc_change * 10.0) / 10.0,
is_anomaly: if math.abs(x: soc_change) > 3.0 then 1.0 else 0.0
}
})
|> sort(columns: ["_time"])
|> group()
|> yield(name: "soc_changes")