Skip to content

Commit 13307f8

Browse files
committed
feat(#151): static relative start / end dates instead of using energy-date-selector
By popular demand, we now have `time_period_from` & `time_period_to` options. Format is similar to Grafana. See the README
1 parent 46ea331 commit 13307f8

File tree

9 files changed

+235
-86
lines changed

9 files changed

+235
-86
lines changed

README.md

Lines changed: 55 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ Install through [HACS](https://hacs.xyz/)
2727
| autoconfig | object | | Experimental. See [autoconfig](#autoconfig)
2828
| sections | list | | Required unless using autoconfig. Entities to show divided by sections, see [sections object](#sections-object) for additional options.
2929
| layout | string | auto | Valid options are: 'horizontal' - flow left to right, 'vertical' - flow top to bottom & 'auto' - determine based on available space (based on the section->`min_witdh` option, which defaults to 150)
30-
| energy_date_selection | boolean | false | Integrate with the Energy Dashboard. Filters data based on the [energy-date-selection](https://www.home-assistant.io/dashboards/energy/) card. Use this only for accumulated data sensors (energy/water/gas) and with a `type:energy-date-selection` card. You still need to specify all your entities as HA doesn't know exactly how to connect them but you can use the general kWh entities that you have in the energy dashboard. In the future we may use areas to auto configure the chart.
30+
| energy_date_selection | boolean | false | Integrate with the Energy Dashboard. Filters data based on the [energy-date-selection](https://www.home-assistant.io/dashboards/energy/) card. Use this only for accumulated data sensors (energy/water/gas) and with a `type:energy-date-selection` card. You still need to specify all your entities as HA doesn't know exactly how to connect them but you can use the general kWh entities that you have in the energy dashboard. In the future we may use areas to auto configure the chart. Not compatible with `time_period`
3131
| title | string | | Optional header title for the card
3232
| unit_prefix | string | | Metric prefix for the unit of measurment. See <https://en.wikipedia.org/wiki/Unit_prefix> . Supported values are m, k, M, G, T
3333
| round | number | 0 | Round the value to at most N decimal places. May not apply to near zero values, see issue [#29](https://github.com/MindFreeze/ha-sankey-chart/issues/29)
@@ -50,6 +50,8 @@ Install through [HACS](https://hacs.xyz/)
5050
| monetary_unit | string | | Currency of the gas or electricity price, e.g. 'USD'
5151
| sort_by | string | | Sort the entities. Valid options are: 'state'. If your values change often, you may want to use the `throttle` option to limit update frequency
5252
| sort_dir | string | desc | Sorting direction. Valid options are: 'asc' for smallest first & 'desc' for biggest first
53+
| time_period_from | string | | Start of custom time period (e.g., "now-1d", "now/d"). Not compatible with `energy_date_selection`. See [Time period](#time-period)
54+
| time_period_to | string | now | End of custom time period. Not compatible with `energy_date_selection`. See [Time period](#time-period)
5355

5456
### Sections object
5557

@@ -137,10 +139,57 @@ This card supports automatic configuration generation based on the HA energy das
137139
# any additional autoconfig options (listed below)
138140
```
139141

142+
or like this:
143+
144+
```yaml
145+
- type: custom:sankey-chart
146+
autoconfig: true
147+
time_period_from: "now/d" # today
148+
```
149+
140150
| Name | Type | Requirement | Default | Description |
141151
| ----------------- | ------- | ------------ | ------------------- | ------------------------------------------- |
142152
| print_yaml | boolean | **Optional** | false | Prints the auto generated configuration after the card so you can use it as a starting point for customization. It shows up like an error. Don't worry about it.
143153

154+
### Time Period
155+
156+
The `time_period_from` and `time_period_to` options allow you to specify a custom time period for data retrieval. The format is based on [Grafana's time range format](https://grafana.com/docs/grafana/latest/dashboards/use-dashboards/?pg=blog&plcmt=body-txt#set-dashboard-time-range).
157+
158+
Time units: s (seconds), m (minutes), h (hours), d (days), w (weeks), M (months), y (years)
159+
160+
Note that while seconds and minutes are supported, there is a delay in the statistics data in HA of up to 1 hour, so showing small periods like the last 30 mins probably won't work.
161+
162+
Examples:
163+
164+
- `now-5m`: 5 minutes ago
165+
- `now-1h`: 1 hour ago
166+
- `now-1d`: 1 day ago
167+
- `now-1w`: 1 week ago
168+
- `now-1M`: 1 month ago
169+
- `now/d`: Start of the current day
170+
- `now/w`: Start of the current week
171+
- `now/M`: Start of the current month
172+
- `now/y`: Start of the current year
173+
- `now-1d/d`: Start of the previous day
174+
175+
If `time_period_to` is not specified, it defaults to `now`.
176+
177+
Example configurations:
178+
179+
```yaml
180+
type: custom:sankey-chart
181+
title: Last 7 days up to the current moment
182+
time_period_from: "now-7d"
183+
```
184+
185+
```yaml
186+
type: custom:sankey-chart
187+
title: Yesterday
188+
time_period_from: "now-1d/d"
189+
time_period_to: "now/d"
190+
```
191+
192+
144193
## Examples
145194

146195
### Simple
@@ -240,7 +289,7 @@ You can find more examples and help in the HA forum <https://community.home-assi
240289

241290
This card supports partial Energy dashboard integration. You still need to specify the entities and connections for now. See `energy_date_selection` option.
242291

243-
Currently this chart just shows historical data based on a energy-date-selection card. It doesnt know/care if your entities are in the default energy dashboard.
292+
Currently this chart just shows historical data based on a energy-date-selection card. It doesn't know/care if your entities are in the default energy dashboard.
244293

245294
## FAQ
246295

@@ -250,7 +299,7 @@ Currently this chart just shows historical data based on a energy-date-selection
250299

251300
**Q: How do I get total [daily] energy?**
252301

253-
**A:** There isnt a general Consumed Energy sensor in the HA Energy dashboard AFAIK. HA calculates it based on all the in/out kWh values. I cant tell you exactly how to calculate it because it depends on what values you can monitor. Some people already have a Total Consumption sensor, others have a Current Consumption and create an integration sensor from that, etc.
302+
**A:** There isn't a general Consumed Energy sensor in the HA Energy dashboard AFAIK. HA calculates it based on all the in/out kWh values. I can't tell you exactly how to calculate it because it depends on what values you can monitor. Some people already have a Total Consumption sensor, others have a Current Consumption and create an integration sensor from that, etc.
254303

255304
**Q: Can I group/sum entities in the chart?**
256305

@@ -273,11 +322,11 @@ Currently this chart just shows historical data based on a energy-date-selection
273322
1. `npm i`
274323
2. `npm start`
275324
3. The compiled `.js` file will be accessible on
276-
`http://127.0.0.1:5000/ha-sankey-chart.js`.
325+
`http://127.0.0.1:3000/ha-sankey-chart.js`.
277326
4. On a running Home Assistant installation add this to your Lovelace `resources:`
278327

279328
```yaml
280-
- url: 'http://127.0.0.1:5000/ha-sankey-chart.js'
329+
- url: 'http://127.0.0.1:3000/ha-sankey-chart.js'
281330
type: module
282331
```
283332

@@ -287,3 +336,4 @@ Currently this chart just shows historical data based on a energy-date-selection
287336
[maintenance-shield]: https://img.shields.io/maintenance/yes/2024.svg?style=for-the-badge
288337
[releases-shield]: https://img.shields.io/github/release/MindFreeze/ha-sankey-chart.svg?style=for-the-badge
289338
[releases]: https://github.com/MindFreeze/ha-sankey-chart/releases
339+

rollup.config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const dev = process.env.ROLLUP_WATCH;
1212
const serveopts = {
1313
contentBase: ['./dist'],
1414
host: '0.0.0.0',
15-
port: 5000,
15+
port: 3000,
1616
allowCrossOrigin: true,
1717
headers: {
1818
'Access-Control-Allow-Origin': '*',

src/editor/index.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,12 @@ export class SankeyChartEditor extends LitElement implements LovelaceCardEditor
7373
};
7474
}
7575
} else {
76+
if (ev.detail.value.time_period_from && !this._config!.time_period_from) {
77+
ev.detail.value.energy_date_selection = false;
78+
} else if (ev.detail.value.energy_date_selection && !this._config!.energy_date_selection) {
79+
ev.detail.value.time_period_from = undefined;
80+
ev.detail.value.time_period_to = undefined;
81+
}
7682
this._config = { ...ev.detail.value };
7783
}
7884
this._updateConfig();
@@ -164,15 +170,17 @@ export class SankeyChartEditor extends LitElement implements LovelaceCardEditor
164170
// ],
165171
// },
166172
{ name: 'title', selector: { text: {} } },
167-
{ name: 'show_names', selector: { boolean: {} } },
168-
{ name: 'show_icons', selector: { boolean: {} } },
169-
{ name: 'show_states', selector: { boolean: {} } },
170-
{ name: 'show_units', selector: { boolean: {} } },
171173
{ name: 'energy_date_selection', selector: { boolean: {} } },
172174
{
173175
type: 'grid',
174176
name: '',
175177
schema: [
178+
{ name: 'time_period_from', selector: { text: {} } },
179+
{ name: 'time_period_to', selector: { text: {} } },
180+
{ name: 'show_names', selector: { boolean: {} } },
181+
{ name: 'show_icons', selector: { boolean: {} } },
182+
{ name: 'show_states', selector: { boolean: {} } },
183+
{ name: 'show_units', selector: { boolean: {} } },
176184
{
177185
name: 'layout',
178186
selector: {

src/energy.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,15 @@ export const getEnergyDataCollection = (
103103
if ((hass.connection as any)[key]) {
104104
return (hass.connection as any)[key];
105105
}
106-
// HA has not initialized the collection yet and we don't want to interfere with that
106+
// HA has not initialized the collection yet and we don't want to interfere with that if energy_date_selection is enabled
107107
return null;
108108
};
109109

110+
export const getEnergyPreferences = (hass: HomeAssistant) =>
111+
hass.callWS<EnergyPreferences>({
112+
type: "energy/get_prefs",
113+
});
114+
110115

111116
const fetchStatistics = (
112117
hass: HomeAssistant,
@@ -175,10 +180,10 @@ const calculateStatisticSumGrowth = (
175180
return growth;
176181
};
177182

178-
export async function getStatistics(hass: HomeAssistant, energyData: EnergyData, devices: string[], conversions: Conversions): Promise<Record<string, number>> {
183+
export async function getStatistics(hass: HomeAssistant, { start, end }: Pick<EnergyData, 'start' | 'end'>, devices: string[], conversions: Conversions): Promise<Record<string, number>> {
179184
const dayDifference = differenceInDays(
180-
energyData.end || new Date(),
181-
energyData.start
185+
end || new Date(),
186+
start
182187
);
183188
const period = dayDifference > 35 ? "month" : dayDifference > 2 ? "day" : "hour";
184189

@@ -190,10 +195,10 @@ export async function getStatistics(hass: HomeAssistant, energyData: EnergyData,
190195
// If converting from kWh to CO2, we need to use a different API call to account for time-varying CO2 intensity
191196
time_variant_data[id] = fetchFossilEnergyConsumption(
192197
hass,
193-
energyData.start,
198+
start,
194199
[id],
195200
conversions.co2_intensity_entity,
196-
energyData.end,
201+
end,
197202
period
198203
);
199204
}
@@ -211,8 +216,8 @@ export async function getStatistics(hass: HomeAssistant, energyData: EnergyData,
211216
if (time_invariant_devices.length > 0) {
212217
time_invariant_data = await fetchStatistics(
213218
hass,
214-
energyData.start,
215-
energyData.end,
219+
start,
220+
end,
216221
time_invariant_devices,
217222
period,
218223
// units,

0 commit comments

Comments
 (0)