diff --git a/README.md b/README.md index 5c21181..3d85da4 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ Install through [HACS](https://hacs.xyz/) | sort_dir | string | desc | Sorting direction. Valid options are: 'asc' for smallest first & 'desc' for biggest first | 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) | time_period_to | string | now | End of custom time period. Not compatible with `energy_date_selection`. See [Time period](#time-period) +| ignore_missing_entities | boolean | false | If true, missing entities will be treated as having a state of 0 instead of throwing an error | ### Sections object diff --git a/__tests__/basic.test.ts b/__tests__/basic.test.ts index fc425ef..6788b61 100644 --- a/__tests__/basic.test.ts +++ b/__tests__/basic.test.ts @@ -31,8 +31,9 @@ const hass = mockHass({ }, }); +const ROOT_TAG = 'sankey-chart'; + describe('SankeyChart', () => { - const ROOT_TAG = 'sankey-chart'; let sankeyChart: SankeyChart; beforeEach(() => { @@ -72,3 +73,37 @@ describe('SankeyChart', () => { expect(sankeyChartBase.shadowRoot?.innerHTML.replace(//g, '')).toMatchSnapshot(); }); }); + +describe('Missing entities', () => { + let element: SankeyChart; + + beforeEach(() => { + element = document.createElement(ROOT_TAG) as SankeyChart; + // @ts-ignore + element.hass = hass as HomeAssistant; + }); + + test('treats missing entity as 0 when ignore_missing_entities is true', () => { + const config = { + type: 'custom:sankey-chart', + ignore_missing_entities: true, + sections: [ + { + entities: [ + { + entity_id: 'sensor.missing', + children: ['sensor.ent2'], + }, + ], + }, + { + entities: ['sensor.ent2'], + }, + ], + }; + + element.setConfig(config, true); + // Should not throw + expect(() => element.requestUpdate()).not.toThrow(); + }); +}); diff --git a/src/chart.ts b/src/chart.ts index 9dd3ca3..dd90a99 100644 --- a/src/chart.ts +++ b/src/chart.ts @@ -568,6 +568,16 @@ export class Chart extends LitElement { let entity = this.states[getEntityId(entityConf)]; if (!entity) { + if (this.config.ignore_missing_entities) { + // Return a fake entity with state 0 if ignoring missing entities + return { + state: 0, + attributes: { + unit_of_measurement: entityConf.unit_of_measurement || '', + friendly_name: entityConf.name || getEntityId(entityConf), + }, + }; + } throw new Error('Entity not found "' + getEntityId(entityConf) + '"'); } diff --git a/src/types.ts b/src/types.ts index 5e8b9bc..d6b3b1c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -41,6 +41,7 @@ export interface SankeyChartConfig extends LovelaceCardConfig { sort_dir?: 'asc' | 'desc'; time_period_from?: string; time_period_to?: string; + ignore_missing_entities?: boolean; } declare global {