Skip to content

Commit f08ae9e

Browse files
committed
Pass hass object to filters
1 parent 6b131a0 commit f08ae9e

File tree

3 files changed

+46
-28
lines changed

3 files changed

+46
-28
lines changed

readme.md

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ You may find some extra info there in this link
2929

3030
Find more advanced examples in [Show & Tell](https://github.com/dbuezas/lovelace-plotly-graph-card/discussions/categories/show-and-tell)
3131

32-
## Installation
32+
## Installation
3333

3434
### Via Home Assistant Community Store (Recommended)
3535

@@ -41,13 +41,13 @@ Find more advanced examples in [Show & Tell](https://github.com/dbuezas/lovelace
4141
1. Go to [Releases](https://github.com/dbuezas/lovelace-plotly-graph-card/releases)
4242
2. Download `plotly-graph-card.js` and copy it to your Home Assistant config dir as `<config>/www/plotly-graph-card.js`
4343
3. Add a resource to your dashboard configuration. There are two ways:
44-
1. **Using UI**: `Settings``Dashboards``More Options icon``Resources``Add Resource` → Set Url as `/local/plotly-graph-card.js` → Set Resource type as `JavaScript Module`.
45-
*Note: If you do not see the Resources menu, you will need to enable Advanced Mode in your User Profile*
46-
2. **Using YAML**: Add following code to lovelace section.
47-
```resources:
48-
- url: /local/plotly-graph-card.js
49-
type: module
50-
```
44+
1. **Using UI**: `Settings``Dashboards``More Options icon``Resources``Add Resource` → Set Url as `/local/plotly-graph-card.js` → Set Resource type as `JavaScript Module`.
45+
_Note: If you do not see the Resources menu, you will need to enable Advanced Mode in your User Profile_
46+
2. **Using YAML**: Add following code to lovelace section.
47+
```resources:
48+
- url: /local/plotly-graph-card.js
49+
type: module
50+
```
5151
5252
## Card Config
5353
@@ -439,15 +439,15 @@ entities:
439439
alpha: 0.1 # between 0 an 1. The lower the alpha, the smoother the trace.
440440
441441
# The filters below receive all datapoints as they come from home assistant. Y values are strings or null (unless previously mapped to numbers or any other type)
442-
- map_y: y === "heat" ? 1 : 0 # map the y values of each datapoint. Variables `i` (index), `x`, `state`, `statistic` and `meta` and `vars` are also in scope.
442+
- map_y: y === "heat" ? 1 : 0 # map the y values of each datapoint. Variables `i` (index), `x`, `y`, `state`, `statistic`, `meta`, `vars` and `hass` are in scope.
443443
- map_x: new Date(+x + 1000) # map the x coordinate (javascript date object) of each datapoint. Same variables as map_y are in scope
444444
- fn: |- # arbitrary function. Only the keys that are returned are replaced. Returning null or undefined, leaves the data unchanged (useful )
445445
446-
({xs, ys, meta, states, statistics}) => {
446+
({xs, ys, meta, states, statistics, hass}) => {
447447
# either statistics or states will be available, depending on if "statistics" are fetched or not
448448
# attributes will be available inside states only if an attribute is picked in the trace
449449
return {
450-
ys: states.map(state => +state?.attributes?.current_temperature - state?.attributes?.target_temperature),
450+
ys: states.map(state => +state?.attributes?.current_temperature - state?.attributes?.target_temperature + hass.states.get("sensor.inside_temp")),
451451
meta: { unit_of_measurement: "delta" }
452452
};
453453
},
@@ -540,12 +540,24 @@ or alternatively,
540540
}
541541
```
542542

543+
##### Using the hass object
544+
545+
Funcitonal filters receive `hass` (Home Assistant) as parameter, which gives you access to the current states of all entities.
546+
547+
```yaml
548+
type: custom:plotly-graph
549+
entities:
550+
- entity: sensor.power_consumption
551+
filters:
552+
- map_y: parseFloat(y) * parseFloat(hass.states['sensor.cost'].state)
553+
```
554+
543555
##### Using vars
544556

545557
Compute absolute humidity
546558

547559
```yaml
548-
type: custom:plotly-graph-dev
560+
type: custom:plotly-graph
549561
entities:
550562
- entity: sensor.wintergarten_clima_humidity
551563
internal: true
@@ -566,7 +578,7 @@ entities:
566578
Compute dew point
567579

568580
```yaml
569-
type: custom:plotly-graph-dev
581+
type: custom:plotly-graph
570582
entities:
571583
- entity: sensor.openweathermap_humidity
572584
internal: true
@@ -715,7 +727,7 @@ refresh_interval: 5 # update every 5 seconds
715727
- run `npm i`
716728
- run `npm start`
717729
- From a dashboard in edit mode, go to `Manage resources` and add `http://127.0.0.1:8000/plotly-graph-card.js` as url with resource type JavaScript
718-
- ATTENTION: The development card is `type: custom:plotly-graph-dev`
730+
- ATTENTION: The development card is `type: custom:plotly-graph`
719731
- Either use Safari or Enable [chrome://flags/#unsafely-treat-insecure-origin-as-secure](chrome://flags/#unsafely-treat-insecure-origin-as-secure) and add your HA address (e.g http://homeassistant.local:8123): Chrome doesn't allow public network resources from requesting private-network resources - unless the public-network resource is secure (HTTPS) and the private-network resource provides appropriate (yet-undefined) CORS headers. More [here](https://stackoverflow.com/questions/66534759/chrome-cors-error-on-request-to-localhost-dev-server-from-remote-site)
720732

721733
# Build

src/filters/filters.ts

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Datum } from "plotly.js";
1+
import { HomeAssistant } from "custom-card-helpers";
22
import { linearRegressionLine, linearRegression } from "simple-statistics";
33
import {
44
parseTimeDuration,
@@ -18,6 +18,7 @@ type FilterData = {
1818
statistics: StatisticValue[];
1919
meta: HassEntity["attributes"];
2020
vars: Record<any, any>;
21+
hass: HomeAssistant;
2122
};
2223
export type FilterFn = (p: FilterData) => Partial<FilterData>;
2324

@@ -192,26 +193,30 @@ const filters = {
192193
};
193194
},
194195
map_y_numbers: (fnStr: string) => {
195-
const fn = myEval(`(i, x, y, state, statistic, vars) => ${fnStr}`);
196-
return ({ xs, ys, states, statistics, vars }) => ({
196+
const fn = myEval(`(i, x, y, state, statistic, vars, hass) => ${fnStr}`);
197+
return ({ xs, ys, states, statistics, vars, hass }) => ({
197198
xs,
198199
ys: mapNumbers(ys, (y, i) =>
199-
fn(i, xs[i], y, states[i], statistics[i], vars)
200+
fn(i, xs[i], y, states[i], statistics[i], vars, hass)
200201
),
201202
});
202203
},
203204
map_y: (fnStr: string) => {
204-
const fn = myEval(`(i, x, y, state, statistic, vars) => ${fnStr}`);
205-
return ({ xs, ys, states, statistics, vars }) => ({
205+
const fn = myEval(`(i, x, y, state, statistic, vars, hass) => ${fnStr}`);
206+
return ({ xs, ys, states, statistics, vars, hass }) => ({
206207
xs,
207-
ys: ys.map((_, i) => fn(i, xs[i], ys[i], states[i], statistics[i], vars)),
208+
ys: ys.map((_, i) =>
209+
fn(i, xs[i], ys[i], states[i], statistics[i], vars, hass)
210+
),
208211
});
209212
},
210213
map_x: (fnStr: string) => {
211-
const fn = myEval(`(i, x, y, state, statistic, vars) => ${fnStr}`);
212-
return ({ xs, ys, states, statistics, vars }) => ({
214+
const fn = myEval(`(i, x, y, state, statistic, vars, hass) => ${fnStr}`);
215+
return ({ xs, ys, states, statistics, vars, hass }) => ({
213216
ys,
214-
xs: xs.map((_, i) => fn(i, xs[i], ys[i], states[i], statistics[i], vars)),
217+
xs: xs.map((_, i) =>
218+
fn(i, xs[i], ys[i], states[i], statistics[i], vars, hass)
219+
),
215220
});
216221
},
217222
resample:
@@ -240,16 +245,16 @@ const filters = {
240245
},
241246
store_var:
242247
(var_name: string) =>
243-
({ vars, ...rest }) => ({ vars: { ...vars, [var_name]: rest } }),
248+
({ hass, vars, ...rest }) => ({ vars: { ...vars, [var_name]: rest } }),
244249
/*
245250
example: fn("({xs, ys, states, statistics }) => ({xs: ys})")
246251
*/
247252
fn: (fnStr: string) => myEval(fnStr),
248253
filter: (fnStr: string) => {
249-
const fn = myEval(`(i, x, y, state, statistic, vars) => ${fnStr}`);
250-
return ({ xs, ys, states, statistics, vars }) => {
254+
const fn = myEval(`(i, x, y, state, statistic, vars, hass) => ${fnStr}`);
255+
return ({ xs, ys, states, statistics, vars, hass }) => {
251256
const mask = ys.map((_, i) =>
252-
fn(i, xs[i], ys[i], states[i], statistics[i], vars)
257+
fn(i, xs[i], ys[i], states[i], statistics[i], vars, hass)
253258
);
254259
return {
255260
ys: ys.filter((_, i) => mask[i]),

src/plotly-graph-card.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ export class PlotlyGraph extends HTMLElement {
431431
...this.cache.getData(trace),
432432
meta,
433433
vars,
434+
hass: this.hass!,
434435
};
435436
if (!this.isBrowsing) {
436437
// to ensure the y axis autoranges to the visible data

0 commit comments

Comments
 (0)