lovelace-plotly-graph-card icon indicating copy to clipboard operation
lovelace-plotly-graph-card copied to clipboard

Support long-term statistics

Open FrnchFrgg opened this issue 3 years ago • 1 comments

It would be worthwhile to support long-term statistics for entities that support it. There needs to be options to toggle statistics mode on and off, select between the mean, max, min or sum, and select between the period hour, day or month (there is 5min too IIRC).

Apex-charts card already supports long-term statistics. See https://github.com/RomRider/apexcharts-card/blob/master/src/graphEntry.ts#L257 for the if/else clauses with first statistics fetching then normal history fetching. AFAICT the difference is not much and mostly in _fetchStatistics vs _fetchRecent even though the value of the datapoint then comes from entry[period] instead of entry.state or an attribute, and the time is gotten from start/end attributes instead of entry.last_changed/entry.last_updated. To me it seems that it is not too hard to retrofit the statistics fetching into the format output by fetchSingleRange() at https://github.com/dbuezas/lovelace-plotly-graph-card/blob/master/src/Cache.ts#L13

Some example JS code that actually fetches statistics data, filters it and returns a list of [timestamp, value] pairs:

      const statistics = await hass.callWS({
          type: 'recorder/statistics_during_period',
          start_time: new Date(start).toISOString(),
          end_time: new Date(end).toISOString(),
          statistic_ids: [entity.entity_id],
          period: "hour",
      });
      var result = [];
      statistics[entity.entity_id].forEach( (item) => {
        val = parseFloat(item.mean)
        if (val > 100) {
           result.push([
            ((new Date(mid.start).getTime()) + (new Date(mid.end).getTime()))/2,
            val
          ])
        }
      });
      return result;

It is adapted from https://gitlab.com/home-assistant-frnchfrgg/apex-local-extrema/-/blob/main/apex.yaml that I use in production currently (but lovelace-ploty-graph-card has features I hope to use, in particular your data mangling feature is not per-point so I could do all this without abusing a data generator).

I would do it myself in a pull request (and maybe will) but since you embed the history entry into the result I would have to check all around what fields you expect to see in users of the cache.

FrnchFrgg avatar Oct 14 '22 15:10 FrnchFrgg

Hey thanks for the well researched pointers, I'll use that as a base :)

dbuezas avatar Oct 14 '22 20:10 dbuezas

I'm starting to use this myself :)

dbuezas avatar Oct 28 '22 10:10 dbuezas