library(influxdbclient)
token <- "XPBViJ3s4JL9_wPffwd5M2EgXj5hcUgT0n4jNhv7m6-NC-6SSxQ3run4kXtWBvOk-FYr1VG5Tj5WcoHgjge9jw=="
org <- "laempe"
bucket <- "energy-monitor"

client <- InfluxDBClient$new(url = "http://influxdb:8086",
                             token = token,
                             org = org)

get_df <- function(client, query) {
  result <- client$query(gsub("[\r\n]", "", query))
  
  time <- result[["_result"]][[1]][["time"]]
  
  df <- data.frame(time)
  
  for (i in 1:length(result[["_result"]])){
    r <- result[["_result"]][[i]]
    if(exists("channel", r))
      field <- sprintf('%s_%s', r[["_field"]][1], r[["channel"]][1])
    else
      field <- r[["_field"]][1]
    df[field] <- r[["_value"]]
  }
  rm(result) 
  return(df)
}

start = "2022-05-04T06:00:00+02:00"
stop  = "2022-05-04T11:25:00+02:00"
query = sprintf('
from(bucket: "energy-monitor")
  |> range(start: %s, stop: %s)
  |> filter(fn: (r) => r["_measurement"] == "plant")
  |> filter(fn: (r) => r["_field"] == "auswerfer_1_heben" or r["_field"] == "auswerfer_1_senken" or r["_field"] == "gaswagen_ausfahren" or r["_field"] == "gaswagen_einfahren" or r["_field"] == "hubtisch_heben" or r["_field"] == "hubtisch_senken" or r["_field"] == "rolltor_oeffnen" or r["_field"] == "rolltor_schliessen" or r["_field"] == "schuss" or r["_field"] == "seitenteil_links_schliessen" or r["_field"] == "seitenteil_links_und_rechts_oeffnen" or r["_field"] == "seitenteil_rechts_schliessen" or r["_field"] == "unterteil_faehrt_aus" or r["_field"] == "unterteil_faehrt_ein")
  |> aggregateWindow(every: 50ms, fn: last, createEmpty: false)
  |> toBool()
  |> yield(name: "last")
  |> drop(columns: ["_start", "_stop"])
', start, stop)

hengli_plant = get_df(client, query)

query = sprintf('
from(bucket: "energy-monitor")
  |> range(start: %s, stop: %s)
  |> filter(fn: (r) => r["_measurement"] == "24v")
  |> filter(fn: (r) => r["_field"] == "current" or r["_field"] == "voltage")
  |> aggregateWindow(every: 20ms, fn: mean, createEmpty: false)
  |> yield(name: "mean")
  |> drop(columns: ["_start", "_stop"])
', start, stop)

hengli_24v = get_df(client, query)

query = sprintf('
from(bucket: "energy-monitor")
  |> range(start: %s, stop: %s)
  |> filter(fn: (r) => r["_measurement"] == "480v")
  |> aggregateWindow(every: 60ms, fn: mean, createEmpty: false)
  |> yield(name: "mean")
  |> drop(columns: ["_start", "_stop"])
', start, stop)

hengli_480v = get_df(client, query)

