-
Notifications
You must be signed in to change notification settings - Fork 22
/
octopus-energy-rates-card.js
501 lines (454 loc) · 20.1 KB
/
octopus-energy-rates-card.js
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class OctopusEnergyRatesCard extends HTMLElement {
set hass(hass) {
const config = this._config;
if (!this.content) {
const card = document.createElement('ha-card');
card.header = config.title;
this.content = document.createElement('div');
this.content.style.padding = '0 16px 16px';
const style = document.createElement('style');
style.textContent = `
table {
width: 100%;
padding: 0px;
spacing: 0px;
}
table.sub_table {
border-collapse: seperate;
border-spacing: 0px 2px;
}
table.main {
padding: 0px;
}
td.time_highlight {
font-weight: bold;
color: white;
}
td.current {
position: relative;
}
td.current:before{
content: "";
position: absolute;
top: 0;
right: 0;
width: 0;
height: 0;
display: block;
border-top: calc(var(--paper-font-body1_-_line-height)*0.65) solid transparent;
border-bottom: calc(var(--paper-font-body1_-_line-height)*0.65) solid transparent;
border-right: 10px solid;
}
thead th {
text-align: left;
padding: 0px;
}
td {
vertical-align: top;
padding: 2px;
spacing: 0px;
}
tr.rate_row{
text-align:center;
width:80px;
}
td.time {
text-align:center;
vertical-align: middle;
}
td.time_red{
border-bottom: 1px solid Tomato;
}
td.time_orange{
border-bottom: 1px solid orange;
}
td.time_green{
border-bottom: 1px solid MediumSeaGreen;
}
td.time_lightgreen {
border-bottom: 1px solid ForestGreen;
}
td.time_blue{
border-bottom: 1px solid #391CD9;
}
td.time_cheapest{
border-bottom: 1px solid LightGreen;
}
td.time_cheapestblue{
border-bottom: 1px solid LightBlue;
}
td.rate {
color:white;
text-align:center;
vertical-align: middle;
width:80px;
border-top-right-radius:15px;
border-bottom-right-radius:15px;
}
td.red {
border: 2px solid Tomato;
background-color: Tomato;
}
td.orange {
border: 2px solid orange;
background-color: orange;
}
td.green {
border: 2px solid MediumSeaGreen;
background-color: MediumSeaGreen;
}
td.lightgreen {
border: 2px solid ForestGreen;
background-color: ForestGreen;
}
td.blue {
border: 2px solid #391CD9;
background-color: #391CD9;
}
td.cheapest {
color: black;
border: 2px solid LightGreen;
background-color: LightGreen;
}
td.cheapestblue {
color: black;
border: 2px solid LightBlue;
background-color: LightBlue;
}
`;
card.appendChild(style);
card.appendChild(this.content);
this.appendChild(card);
}
// Initialise the lastRefreshTimestamp
if (!this.lastRefreshTimestamp) {
// Store the timestamp of the last refresh
this.lastRefreshTimestamp = 0;
}
// Check if the interval has passed
const currentTime = Date.now();
const cardRefreshIntervalSecondsInMilliseconds = config.cardRefreshIntervalSeconds * 1000;
if (!(currentTime - this.lastRefreshTimestamp >= cardRefreshIntervalSecondsInMilliseconds)) {
return
}
this.lastRefreshTimestamp = currentTime;
const colours_import = ['lightgreen', 'green', 'orange', 'red', 'blue', 'cheapest', 'cheapestblue'];
const colours_export = ['red', 'green', 'orange', 'green'];
const currentEntityId = config.currentEntity;
const futureEntityId = config.futureEntity;
const pastEntityId = config.pastEntity;
// Create an empty array to store the parsed attributes
const allSlotsTargetTimes = [];
const targetTimesEntities = config.targetTimesEntities && Object.keys(config.targetTimesEntities) || [];
// Iterate through each entity in targetTimesEntities
for (const entityId of targetTimesEntities) {
const entityTimesState = hass.states[entityId];
const entityExtraData = config.targetTimesEntities[entityId] || [];
const backgroundColour = entityExtraData.backgroundColour || "Navy";
const timePrefix = entityExtraData.prefix || "";
// Access the attributes of the current entity
const entityAttributes = entityTimesState ? this.reverseObject(entityTimesState.attributes) : {};
// Get the target_times array, handling potential undefined cases
const targetTimes = entityAttributes.target_times || [];
// Iterate through each target time and push it individually
for (const targetTime of targetTimes) {
allSlotsTargetTimes.push({
start: targetTime.start,
end: targetTime.end,
color: backgroundColour,
timePrefix: timePrefix,
});
}
}
var lowlimit = config.lowlimit;
var mediumlimit = config.mediumlimit;
var highlimit = config.highlimit;
// Check if we've received a number, if not, assume they are entities
// and read them from the state
if (isNaN(lowlimit)) {
lowlimit = parseFloat(hass.states[lowlimit].state)
}
if (isNaN(mediumlimit)) {
mediumlimit = parseFloat(hass.states[mediumlimit].state)
}
if (isNaN(highlimit)) {
highlimit = parseFloat(hass.states[highlimit].state)
}
const unitstr = config.unitstr;
const roundUnits = config.roundUnits;
const showpast = config.showpast;
const showday = config.showday;
const hour12 = config.hour12;
const cheapest = config.cheapest;
const combinerate = config.combinerate;
const multiplier = config.multiplier
const rateListLimit = config.rateListLimit
var colours = (config.exportrates ? colours_export : colours_import);
var rates_totalnumber = 0;
var combinedRates = [];
// Grab the rates which are stored as an attribute of the sensor
const paststate = hass.states[pastEntityId];
const currentstate = hass.states[currentEntityId];
const futurestate = hass.states[futureEntityId];
// Get Limit entity values
const limitEntity = config.limitEntity;
const limitEntityState = hass.states[limitEntity];
const limitHighMult = config.highLimitMultiplier;
const limitMedMult = config.mediumLimitMultiplier;
// Create an empty array to store the parsed attributes
var additionalDynamicLimits = [];
const additionalDynamicLimitsEntities = config.additionalDynamicLimits && Object.keys(config.additionalDynamicLimits) || [];
// Iterate through each entity in additionalDynamicLimitsEntities
for (const entityId of additionalDynamicLimitsEntities) {
const limitExtraData = config.additionalDynamicLimits[entityId] || [];
const backgroundColour = limitExtraData.backgroundColour || "";
const timePrefix = limitExtraData.prefix || "";
const limit = parseFloat(hass.states[entityId].state);
if (!isNaN(limit)) {
additionalDynamicLimits.push({
limit: limit,
color: backgroundColour,
timePrefix: timePrefix,
})
} else {
console.warn("Couldn't parse entity state ${entityId} as a float")
}
}
if (!(limitEntity == null)) {
const limitAve = parseFloat(limitEntityState.state);
mediumlimit = limitAve * limitMedMult;
highlimit = limitAve * limitHighMult;
};
// Combine the data sources
if (typeof (paststate) != 'undefined' && paststate != null) {
const pastattributes = this.reverseObject(paststate.attributes);
var ratesPast = pastattributes.rates;
ratesPast.forEach(function (key) {
combinedRates.push(key);
rates_totalnumber++;
});
}
if (typeof (currentstate) != 'undefined' && currentstate != null) {
const currentattributes = this.reverseObject(currentstate.attributes);
var ratesCurrent = currentattributes.rates;
ratesCurrent.forEach(function (key) {
combinedRates.push(key);
rates_totalnumber++;
});
}
// Check to see if the 'rates' attribute exists on the chosen entity. If not, either the wrong entity
// was chosen or there's something wrong with the integration.
// The rates attribute also appears to be missing after a restart for a while - please see:
// https://github.com/BottlecapDave/HomeAssistant-OctopusEnergy/issues/135
if (!ratesCurrent) {
throw new Error("There are no rates assigned to that entity! Please check integration or chosen entity");
}
if (typeof (futurestate) != 'undefined' && futurestate != null) {
const futureattributes = this.reverseObject(futurestate.attributes);
var ratesFuture = futureattributes.rates;
ratesFuture.forEach(function (key) {
combinedRates.push(key);
rates_totalnumber++;
});
}
// This is critical to breaking down the columns properly. For now, there's now
// two loops doing the same thing which is not ideal.
// TODO: there should be one clear data process loop and one rendering loop? Or a function?
var rates_list_length = 0;
var cheapest_rate = 5000;
var previous_rate = 0;
var rates_currentNumber = 0;
var previous_rates_day = "";
var rates_processingRow = 0;
var filteredRates = [];
// filter out rates to display
combinedRates.forEach(function (key) {
const date_milli = Date.parse(key.start);
var date = new Date(date_milli);
const lang = navigator.language || navigator.languages[0];
var current_rates_day = date.toLocaleDateString(lang, { weekday: 'short' });
rates_processingRow++;
var ratesToEvaluate = key.value_inc_vat * multiplier;
if ((showpast || (date - Date.parse(new Date()) > -1800000)) && (rateListLimit == 0 || rates_list_length < rateListLimit)) {
rates_currentNumber++;
// Find the cheapest rate that hasn't past yet
if ((ratesToEvaluate < cheapest_rate) && (date - Date.parse(new Date()) > -1800000)) cheapest_rate = ratesToEvaluate;
// If we don't want to combine same values rates then just push them to new display array
if (!combinerate) {
filteredRates.push(key);
rates_list_length++;
}
if (combinerate &&
(
(rates_currentNumber == 1)
|| (current_rates_day != previous_rates_day)
|| (previous_rate != ratesToEvaluate)
)
) {
filteredRates.push(key);
rates_list_length++;
}
previous_rate = ratesToEvaluate;
previous_rates_day = current_rates_day;
}
});
const rows_per_col = Math.ceil(rates_list_length / config.cols);
var tables = "";
tables = tables.concat("<td><table class='sub_table'><tbody>");
var table = ""
var x = 1;
filteredRates.forEach(function (key) {
const date_milli = Date.parse(key.start);
var date = new Date(date_milli);
const lang = navigator.language || navigator.languages[0];
var options = { hourCycle: 'h23', hour12: hour12, hour: '2-digit', minute: '2-digit' };
// The time formatted in the user's Locale
var time_locale = date.toLocaleTimeString(lang, options);
// If the showday config option is set, include the shortened weekday name in the user's Locale
var date_locale = (showday ? date.toLocaleDateString(lang, { weekday: 'short' }) + ' ' : '');
var colour = colours[1]; // Default to 'green' (index 1) (below low limit above 0)
var isTargetTime = false;
var targetTimeBackgroundColor = "";
var targetTimePrefix = "";
// Check if the current time row corresponds to a target time
allSlotsTargetTimes.forEach(function (targetTime) {
const startTime = new Date(targetTime.start);
const endTime = new Date(targetTime.end);
if (date >= startTime && date < endTime) {
isTargetTime = true;
targetTimeBackgroundColor = "' style='background-color: " + targetTime.color + ";";
targetTimePrefix = targetTime.timePrefix ? targetTimePrefix + targetTime.timePrefix : targetTimePrefix;
}
});
// Check if we've got any variable limits defined which will take precedence
additionalDynamicLimits.forEach(function (targetLimit) {
if (key.value_inc_vat <= targetLimit.limit) {
isTargetTime = true;
targetTimeBackgroundColor = "' style='background-color: " + targetLimit.color + ";";
targetTimePrefix = targetLimit.timePrefix ? targetTimePrefix + targetLimit.timePrefix : targetTimePrefix;
}
});
// Add the extra space at the end of the prefix if it's not empty
targetTimePrefix = targetTimePrefix ? targetTimePrefix + " " : targetTimePrefix;
var isCurrentTime = false;
if ((date - Date.parse(new Date()) > -1800000) && (date < new Date())) {
if (showpast) {
isCurrentTime = true;
};
};
var valueToDisplay = key.value_inc_vat * multiplier;
// Apply bold styling if the current time is a target time
var boldStyle = isCurrentTime ? "current " : "";
boldStyle = isTargetTime ? boldStyle + "time_highlight" : boldStyle + "";
if (cheapest && (valueToDisplay == cheapest_rate && cheapest_rate > 0)) colour = colours[5];
else if (cheapest && (valueToDisplay == cheapest_rate && cheapest_rate <= 0)) colour = colours[6];
else if (valueToDisplay > highlimit) colour = colours[3]; //red (import) / green (export)
else if (valueToDisplay > mediumlimit) colour = colours[2]; // orange (import) / orange (export)
else if (valueToDisplay > lowlimit) colour = colours[0]; // lightgreen (import) / red (export)
else if (valueToDisplay <= 0) colour = colours[4]; // below 0 - blue (import/export)
if (showpast || (date - Date.parse(new Date()) > -1800000)) {
table = table.concat("<tr class='rate_row'><td class='time " + boldStyle + " " + "time_" + colour + targetTimeBackgroundColor + "'>" + targetTimePrefix + date_locale + time_locale +
"</td><td class='rate " + colour + "'>" + valueToDisplay.toFixed(roundUnits) + unitstr + "</td></tr>");
if (x % rows_per_col == 0) {
tables = tables.concat(table);
table = "";
if (rates_list_length != x) {
tables = tables.concat("</tbody></table></td>");
tables = tables.concat("<td><table class='sub_table'><tbody>");
}
};
x++;
}
});
tables = tables.concat(table);
tables = tables.concat("</tbody></table></td>");
this.content.innerHTML = `
<table class="main">
<tr>
${tables}
</tr>
</table>
`;
}
reverseObject(object) {
var newObject = {};
var keys = [];
for (var key in object) {
keys.push(key);
}
for (var i = keys.length - 1; i >= 0; i--) {
var value = object[keys[i]];
newObject[keys[i]] = value;
}
return newObject;
}
setConfig(config) {
if (!config.currentEntity) {
throw new Error('You need to define an entity');
}
const defaultConfig = {
targetTimesEntities: null,
// Additional limits specified in a similar format as targetTimesEntities
// but they take input_numbers as input
additionalDynamicLimits: null,
// Controls how many columns the rates split in to
cols: 1,
// Show rates that already happened in the card
showpast: false,
// Show the day of the week with the time
showday: false,
// Use 12 or 24 hour time
hour12: true,
// Controls the title of the card
title: 'Agile Rates',
// Colour controls:
// If the price is above highlimit, the row is marked red.
// If the price is above mediumlimit, the row is marked orange.
// If the price is above lowlimit, the row is marked dark green.
// If the price is below lowlimit, the row is marked green.
// If the price is below 0, the row is marked blue.
lowlimit: 5,
mediumlimit: 20,
highlimit: 30,
// Entity to use for dynamic limits, above are ignored if limitEntity is set.
limitEntity: null,
highLimitMultiplier: 1.1,
mediumLimitMultiplier: 0.8,
// Controls the rounding of the units of the rate
roundUnits: 2,
// The unit string to show if units are shown after each rate
unitstr: 'p/kWh',
// Make the colouring happen in reverse, for export rates
exportrates: false,
// Higlight the cheapest rate
cheapest: false,
// Combine equal rates
combinerate: false,
// multiple rate values for pence (100) or pounds (1)
multiplier: 100,
// Limit display to next X rows
rateListLimit: 0,
// How often should the card refresh in seconds
cardRefreshIntervalSeconds: 60
};
const cardConfig = {
...defaultConfig,
...config,
};
this._config = cardConfig;
}
// The height of your card. Home Assistant uses this to automatically
// distribute all cards over the available columns.
getCardSize() {
return 3;
}
}
customElements.define('octopus-energy-rates-card', OctopusEnergyRatesCard);
// Configure the preview in the Lovelace card picker
window.customCards = window.customCards || [];
window.customCards.push({
type: 'octopus-energy-rates-card',
name: 'Octopus Energy Rates Card',
preview: false,
description: 'This card displays the energy rates for Octopus Energy',
});