-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
189 lines (170 loc) · 5.02 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { HomeAssistant } from 'custom-card-helpers';
import { Collection } from 'home-assistant-js-websocket';
import { addHours, differenceInDays } from 'date-fns';
interface StatisticsMetaData {
statistics_unit_of_measurement: string | null;
statistic_id: string;
source: string;
name?: string | null;
has_sum: boolean;
has_mean: boolean;
unit_class: string | null;
}
interface ConfigEntry {
entry_id: string;
domain: string;
title: string;
source: string;
state: 'loaded' | 'setup_error' | 'migration_error' | 'setup_retry' | 'not_loaded' | 'failed_unload' | 'setup_in_progress';
supports_options: boolean;
supports_remove_device: boolean;
supports_unload: boolean;
pref_disable_new_entities: boolean;
pref_disable_polling: boolean;
disabled_by: 'user' | null;
reason: string | null;
}
interface FossilEnergyConsumption {
[date: string]: number;
}
export interface EnergyData {
start: Date;
end?: Date;
startCompare?: Date;
endCompare?: Date;
prefs: EnergyPreferences;
info: EnergyInfo;
stats: Statistics;
statsMetadata: Record<string, StatisticsMetaData>;
statsCompare: Statistics;
co2SignalConfigEntry?: ConfigEntry;
co2SignalEntity?: string;
fossilEnergyConsumption?: FossilEnergyConsumption;
fossilEnergyConsumptionCompare?: FossilEnergyConsumption;
}
export interface Statistics {
[statisticId: string]: StatisticValue[];
}
export interface StatisticValue {
statistic_id: string;
start: string;
end: string;
last_reset: string | null;
max: number | null;
mean: number | null;
min: number | null;
sum: number | null;
state: number | null;
}
export interface EnergySource {
type: string;
stat_energy_from?: string;
stat_energy_to?: string;
flow_from?: {
stat_energy_from: string;
}[];
flow_to?: {
stat_energy_to: string;
}[];
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DeviceConsumptionEnergyPreference {
stat_consumption: string;
}
export interface EnergyPreferences {
energy_sources: EnergySource[];
device_consumption: DeviceConsumptionEnergyPreference[];
}
export interface EnergyInfo {
cost_sensors: Record<string, string>;
}
export interface EnergyCollection extends Collection<EnergyData> {
start: Date;
end?: Date;
prefs?: EnergyPreferences;
clearPrefs(): void;
setPeriod(newStart: Date, newEnd?: Date): void;
_refreshTimeout?: number;
_updatePeriodTimeout?: number;
_active: number;
}
export const getEnergyDataCollection = (hass: HomeAssistant, key = '_energy'): EnergyCollection | null => {
if ((hass.connection as any)[key]) {
return (hass.connection as any)[key];
}
// HA has not initialized the collection yet and we don't want to interfere with that
return null;
};
const fetchStatistics = (
hass: HomeAssistant,
startTime: Date,
endTime?: Date,
statistic_ids?: string[],
period: '5minute' | 'hour' | 'day' | 'week' | 'month' = 'hour',
// units?: StatisticsUnitConfiguration
) =>
hass.callWS<Statistics>({
type: 'recorder/statistics_during_period',
start_time: startTime.toISOString(),
end_time: endTime?.toISOString(),
statistic_ids,
period,
// units,
});
const calculateStatisticSumGrowth = (values: StatisticValue[]): number | null => {
if (!values || values.length < 2) {
return null;
}
const endSum = values[values.length - 1].sum;
if (endSum === null) {
return null;
}
const startSum = values[0].sum;
if (startSum === null) {
return endSum;
}
return endSum - startSum;
};
export async function getStatistics(hass: HomeAssistant, energyData: EnergyData, devices: string[]): Promise<Record<string, number>> {
const dayDifference = differenceInDays(energyData.end || new Date(), energyData.start);
const startMinHour = addHours(energyData.start, -1);
const period = dayDifference > 35 ? 'month' : dayDifference > 2 ? 'day' : 'hour';
const data = await fetchStatistics(
hass,
startMinHour,
energyData.end,
devices,
period,
// units
);
Object.values(data).forEach(stat => {
// if the start of the first value is after the requested period, we have the first data point, and should add a zero point
if (stat.length && new Date(stat[0].start) > startMinHour) {
stat.unshift({
...stat[0],
start: startMinHour.toISOString(),
end: startMinHour.toISOString(),
sum: 0,
state: 0,
});
}
});
return devices.reduce(
(states, id) => ({
...states,
[id]: calculateStatisticSumGrowth(data[id]),
}),
{},
);
}
export function getEnergySourceColor(type: string) {
if (type === 'solar') {
return 'var(--warning-color)';
}
if (type === 'battery') {
return 'var(--success-color)';
}
return undefined;
}