-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathmain.js
executable file
·991 lines (891 loc) · 30.1 KB
/
main.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
import { LitElement, html, svg } from 'lit-element';
import localForage from 'localforage/src/localforage';
import Graph from './graph';
import style from './style';
import handleClick from './handleClick';
import {
URL_DOCS,
FONT_SIZE,
FONT_SIZE_HEADER,
MAX_BARS,
ICONS,
DEFAULT_COLORS,
UPDATE_PROPS,
DEFAULT_SHOW,
X, Y, V,
} from './const';
import {
getMin,
getAvg,
getMax,
getTime,
getMilli,
interpolateColor,
compress, decompress,
getFirstDefinedItem,
compareArray,
} from './utils';
localForage.config({
name: 'mini-graph-card',
version: 1.0,
storeName: 'entity_history_cache',
description: 'Mini graph card uses caching for the entity history',
});
localForage.iterate((data, key) => {
const value = key.endsWith('-raw') ? data : decompress(data);
const start = new Date();
start.setHours(start.getHours() - value.hours_to_show);
if (new Date(value.last_fetched) < start) {
localForage.removeItem(key);
}
}).catch((err) => {
// eslint-disable-next-line no-console
console.log('Purging has errored:', err);
});
class MiniGraphCard extends LitElement {
constructor() {
super();
this.id = Math.random()
.toString(36)
.substr(2, 9);
this.config = {};
this.bound = [0, 0];
this.boundSecondary = [0, 0];
this.min = {};
this.avg = {};
this.max = {};
this.length = [];
this.entity = [];
this.line = [];
this.bar = [];
this.fill = [];
this.points = [];
this.gradient = [];
this.tooltip = {};
this.updateQueue = [];
this.updating = false;
this.stateChanged = false;
}
static get styles() {
return style;
}
set hass(hass) {
this._hass = hass;
let updated = false;
this.config.entities.forEach((entity, index) => {
this.config.entities[index].index = index; // Required for filtered views
const entityState = hass.states[entity.entity];
if (entityState && this.entity[index] !== entityState) {
this.entity[index] = entityState;
this.updateQueue.push(entityState.entity_id);
updated = true;
}
});
if (updated) {
this.entity = [...this.entity];
if (!this.config.update_interval && !this.updating) {
this.updateData();
} else {
this.stateChanged = true;
}
}
}
static get properties() {
return {
id: String,
_hass: {},
config: {},
entity: [],
Graph: [],
line: [],
shadow: [],
length: Number,
bound: [],
boundSecondary: [],
abs: [],
tooltip: {},
updateQueue: [],
color: String,
};
}
setConfig(config) {
if (config.entity)
throw new Error(`The "entity" option was removed, please use "entities".\n See ${URL_DOCS}`);
if (!Array.isArray(config.entities))
throw new Error(`Please provide the "entities" option as a list.\n See ${URL_DOCS}`);
if (config.line_color_above || config.line_color_below)
throw new Error(
`"line_color_above/line_color_below" was removed, please use "color_thresholds".\n See ${URL_DOCS}`,
);
const conf = {
animate: false,
hour24: false,
font_size: FONT_SIZE,
font_size_header: FONT_SIZE_HEADER,
height: 100,
hours_to_show: 24,
points_per_hour: 0.5,
aggregate_func: 'avg',
group_by: 'interval',
line_color: [...DEFAULT_COLORS],
color_thresholds: [],
color_thresholds_transition: 'smooth',
line_width: 5,
compress: true,
smoothing: true,
state_map: [],
tap_action: {
action: 'more-info',
},
...config,
show: { ...DEFAULT_SHOW, ...config.show },
};
conf.entities.forEach((entity, i) => {
if (typeof entity === 'string') conf.entities[i] = { entity };
});
conf.state_map.forEach((state, i) => {
// convert string values to objects
if (typeof state === 'string') conf.state_map[i] = { value: state, label: state };
// make sure label is set
conf.state_map[i].label = conf.state_map[i].label || conf.state_map[i].value;
});
if (typeof config.line_color === 'string')
conf.line_color = [config.line_color, ...DEFAULT_COLORS];
conf.font_size = (config.font_size / 100) * FONT_SIZE || FONT_SIZE;
conf.color_thresholds = this.computeThresholds(
conf.color_thresholds,
conf.color_thresholds_transition,
);
const additional = conf.hours_to_show > 24 ? { day: 'numeric', weekday: 'short' } : {};
conf.format = { hour12: !conf.hour24, ...additional };
// override points per hour to mach group_by function
switch (conf.group_by) {
case 'date':
conf.points_per_hour = 1 / 24;
break;
case 'hour':
conf.points_per_hour = 1;
break;
default:
break;
}
if (conf.show.graph === 'bar') {
const entities = conf.entities.length;
if (conf.hours_to_show * conf.points_per_hour * entities > MAX_BARS) {
conf.points_per_hour = MAX_BARS / (conf.hours_to_show * entities);
// eslint-disable-next-line no-console
console.warn(
'mini-graph-card: Not enough space, adjusting points_per_hour to ',
conf.points_per_hour,
);
}
}
const entitiesChanged = !compareArray(this.config.entities || [], conf.entities);
this.config = conf;
if (!this.Graph || entitiesChanged) {
if (this._hass) this.hass = this._hass;
this.Graph = conf.entities.map(
entity => new Graph(
500,
conf.height,
[conf.show.fill ? 0 : conf.line_width, conf.line_width],
conf.hours_to_show,
conf.points_per_hour,
entity.aggregate_func || conf.aggregate_func,
conf.group_by,
getFirstDefinedItem(
entity.smoothing,
config.smoothing,
!entity.entity.startsWith('binary_sensor.'), // turn off for binary sensor by default
),
),
);
}
}
connectedCallback() {
super.connectedCallback();
if (this.config.update_interval) {
this.updateOnInterval();
this.interval = setInterval(
() => this.updateOnInterval(),
this.config.update_interval * 1000,
);
}
}
disconnectedCallback() {
if (this.interval) {
clearInterval(this.interval);
}
super.disconnectedCallback();
}
shouldUpdate(changedProps) {
if (!this.entity[0]) return false;
if (UPDATE_PROPS.some(prop => changedProps.has(prop))) {
this.color = this.intColor(
this.tooltip.value !== undefined ? this.tooltip.value : this.entity[0].state,
this.tooltip.entity || 0,
);
return true;
}
}
updated(changedProperties) {
if (this.config.animate && changedProperties.has('line')) {
if (this.length.length < this.entity.length) {
this.shadowRoot.querySelectorAll('svg path.line').forEach((ele) => {
this.length[ele.id] = ele.getTotalLength();
});
this.length = [...this.length];
} else {
this.length = Array(this.entity.length).fill('none');
}
}
}
render({ config } = this) {
return html`
<ha-card
class="flex"
?group=${config.group}
?fill=${config.show.graph && config.show.fill}
?points=${config.show.points === 'hover'}
?labels=${config.show.labels === 'hover'}
?labels-secondary=${config.show.labels_secondary === 'hover'}
?gradient=${config.color_thresholds.length > 0}
?hover=${config.tap_action.action !== 'none'}
style="font-size: ${config.font_size}px;"
@click=${e => this.handlePopup(e, this.entity[0])}
>
${this.renderHeader()} ${this.renderStates()} ${this.renderGraph()} ${this.renderInfo()}
</ha-card>
`;
}
renderHeader() {
const {
show, align_icon, align_header, font_size_header,
} = this.config;
return show.name || (show.icon && align_icon !== 'state')
? html`
<div class="header flex" loc=${align_header} style="font-size: ${font_size_header}px;">
${this.renderName()} ${align_icon !== 'state' ? this.renderIcon() : ''}
</div>
`
: '';
}
renderIcon() {
const { icon, icon_adaptive_color } = this.config.show;
return icon ? html`
<div class="icon" loc=${this.config.align_icon}
style=${icon_adaptive_color ? `color: ${this.color};` : ''}>
<ha-icon .icon=${this.computeIcon(this.entity[0])}></ha-icon>
</div>
` : '';
}
renderName() {
if (!this.config.show.name) return;
const name = this.tooltip.entity !== undefined
? this.computeName(this.tooltip.entity)
: this.config.name || this.computeName(0);
const color = this.config.show.name_adaptive_color ? `opacity: 1; color: ${this.color};` : '';
return html`
<div class="name flex">
<span class="ellipsis" style=${color}>${name}</span>
</div>
`;
}
renderStates() {
const { entity, value } = this.tooltip;
const state = value !== undefined ? value : this.entity[0].state;
const color = this.config.entities[0].state_adaptive_color ? `color: ${this.color};` : '';
if (this.config.show.state)
return html`
<div class="states flex" loc=${this.config.align_state}>
<div class="state">
<span class="state__value ellipsis" style=${color}>
${this.computeState(state)}
</span>
<span class="state__uom ellipsis" style=${color}>
${this.computeUom(entity || 0)}
</span>
${this.renderStateTime()}
</div>
<div class="states--secondary">${this.config.entities.map((ent, i) => this.renderState(ent, i))}</div>
${this.config.align_icon === 'state' ? this.renderIcon() : ''}
</div>
`;
}
renderState(entity, id) {
if (entity.show_state && id !== 0) {
const { state } = this.entity[id];
return html`
<div
class="state state--small"
@click=${e => this.handlePopup(e, this.entity[id])}
style=${entity.state_adaptive_color ? `color: ${this.computeColor(state, id)};` : ''}>
${entity.show_indicator ? this.renderIndicator(state, id) : ''}
<span class="state__value ellipsis">
${this.computeState(state)}
</span>
<span class="state__uom ellipsis">
${this.computeUom(id)}
</span>
</div>
`;
}
}
renderStateTime() {
if (this.tooltip.value === undefined) return;
return html`
<div class="state__time">
${this.tooltip.label ? html`
<span>${this.tooltip.label}</span>
` : html`
<span>${this.tooltip.time[0]}</span> -
<span>${this.tooltip.time[1]}</span>
`}
</div>
`;
}
renderGraph() {
return this.config.show.graph ? html`
<div class="graph">
<div class="graph__container">
${this.renderLabels()}
${this.renderLabelsSecondary()}
<div class="graph__container__svg">
${this.renderSvg()}
</div>
</div>
${this.renderLegend()}
</div>` : '';
}
renderLegend() {
if (this.visibleLegends.length <= 1 || !this.config.show.legend) return;
return html`
<div class="graph__legend">
${this.visibleLegends.map(entity => html`
<div class="graph__legend__item"
@click=${e => this.handlePopup(e, this.entity[entity.index])}
@mouseover=${() => this.setTooltip(entity.index, -1, this.entity[entity.index].state, 'Current')}
@mouseout=${() => (this.tooltip = {})}>
${this.renderIndicator(this.entity[entity.index].state, entity.index)}
<span class="ellipsis">${this.computeName(entity.index)}</span>
</div>
`)}
</div>
`;
}
renderIndicator(state, index) {
return svg`
<svg width='10' height='10'>
<rect width='10' height='10' fill=${this.intColor(state, index)} />
</svg>
`;
}
renderSvgFill(fill, i) {
if (!fill) return;
const fade = this.config.show.fill === 'fade';
const init = this.length[i] || this.config.entities[i].show_line === false;
return svg`
<defs>
<linearGradient id=${`fill-grad-${this.id}-${i}`} x1="0%" y1="0%" x2="0%" y2="100%">
<stop stop-color='white' offset='0%' stop-opacity='1'/>
<stop stop-color='white' offset='100%' stop-opacity='.15'/>
</linearGradient>
<mask id=${`fill-grad-mask-${this.id}-${i}`}>
<rect width="100%" height="100%" fill=${`url(#fill-grad-${this.id}-${i})`} />
</mask>
</defs>
<mask id=${`fill-${this.id}-${i}`}>
<path class='fill'
type=${this.config.show.fill}
.id=${i} anim=${this.config.animate} ?init=${init}
style="animation-delay: ${this.config.animate ? `${i * 0.5}s` : '0s'}"
fill='white'
mask=${fade ? `url(#fill-grad-mask-${this.id}-${i})` : ''}
d=${this.fill[i]}
/>
</mask>`;
}
renderSvgLine(line, i) {
if (!line) return;
const path = svg`
<path
class='line'
.id=${i}
anim=${this.config.animate} ?init=${this.length[i]}
style="animation-delay: ${this.config.animate ? `${i * 0.5}s` : '0s'}"
fill='none'
stroke-dasharray=${this.length[i] || 'none'} stroke-dashoffset=${this.length[i] || 'none'}
stroke=${'white'}
stroke-width=${this.config.line_width}
d=${this.line[i]}
/>`;
return svg`
<mask id=${`line-${this.id}-${i}`}>
${path}
</mask>
`;
}
renderSvgPoint(point, i) {
const color = this.gradient[i] ? this.computeColor(point[V], i) : 'inherit';
return svg`
<circle
class='line--point'
?inactive=${this.tooltip.index !== point[3]}
style=${`--mcg-hover: ${color};`}
stroke=${color}
fill=${color}
cx=${point[X]} cy=${point[Y]} r=${this.config.line_width}
@mouseover=${() => this.setTooltip(i, point[3], point[V])}
@mouseout=${() => (this.tooltip = {})}
/>
`;
}
renderSvgPoints(points, i) {
if (!points) return;
const color = this.computeColor(this.entity[i].state, i);
return svg`
<g class='line--points'
?tooltip=${this.tooltip.entity === i}
?inactive=${this.tooltip.entity !== undefined && this.tooltip.entity !== i}
?init=${this.length[i]}
anim=${this.config.animate && this.config.show.points !== 'hover'}
style="animation-delay: ${this.config.animate ? `${i * 0.5 + 0.5}s` : '0s'}"
fill=${color}
stroke=${color}
stroke-width=${this.config.line_width / 2}>
${points.map(point => this.renderSvgPoint(point, i))}
</g>`;
}
renderSvgGradient(gradients) {
if (!gradients) return;
const items = gradients.map((gradient, i) => {
if (!gradient) return;
return svg`
<linearGradient id=${`grad-${this.id}-${i}`} gradientTransform="rotate(90)">
${gradient.map(stop => svg`
<stop stop-color=${stop.color} offset=${`${stop.offset}%`} />
`)}
</linearGradient>`;
});
return svg`${items}`;
}
renderSvgLineRect(line, i) {
if (!line) return;
const fill = this.gradient[i]
? `url(#grad-${this.id}-${i})`
: this.computeColor(this.entity[i].state, i);
return svg`
<rect class='line--rect'
?inactive=${this.tooltip.entity !== undefined && this.tooltip.entity !== i}
id=${`rect-${this.id}-${i}`}
fill=${fill} height="100%" width="100%"
mask=${`url(#line-${this.id}-${i})`}
/>`;
}
renderSvgFillRect(fill, i) {
if (!fill) return;
const svgFill = this.gradient[i]
? `url(#grad-${this.id}-${i})`
: this.intColor(this.entity[i].state, i);
return svg`
<rect class='fill--rect'
?inactive=${this.tooltip.entity !== undefined && this.tooltip.entity !== i}
id=${`fill-rect-${this.id}-${i}`}
fill=${svgFill} height="100%" width="100%"
mask=${`url(#fill-${this.id}-${i})`}
/>`;
}
renderSvgBars(bars, index) {
if (!bars) return;
const items = bars.map((bar, i) => {
const animation = this.config.animate
? svg`
<animate attributeName='y' from=${this.config.height} to=${bar.y} dur='1s' fill='remove'
calcMode='spline' keyTimes='0; 1' keySplines='0.215 0.61 0.355 1'>
</animate>`
: '';
const color = this.computeColor(bar.value, index);
return svg`
<rect class='bar' x=${bar.x} y=${bar.y}
height=${bar.height} width=${bar.width} fill=${color}
@mouseover=${() => this.setTooltip(index, i, bar.value)}
@mouseout=${() => (this.tooltip = {})}>
${animation}
</rect>`;
});
return svg`<g class='bars' ?anim=${this.config.animate}>${items}</g>`;
}
renderSvg() {
const { height } = this.config;
return svg`
<svg width='100%' height=${height !== 0 ? '100%' : 0} viewBox='0 0 500 ${height}'
@click=${e => e.stopPropagation()}>
<g>
<defs>
${this.renderSvgGradient(this.gradient)}
</defs>
${this.fill.map((fill, i) => this.renderSvgFill(fill, i))}
${this.fill.map((fill, i) => this.renderSvgFillRect(fill, i))}
${this.line.map((line, i) => this.renderSvgLine(line, i))}
${this.line.map((line, i) => this.renderSvgLineRect(line, i))}
${this.bar.map((bars, i) => this.renderSvgBars(bars, i))}
</g>
${this.points.map((points, i) => this.renderSvgPoints(points, i))}
</svg>`;
}
setTooltip(entity, index, value, label = null) {
const {
points_per_hour,
hours_to_show,
format,
} = this.config;
const offset = hours_to_show < 1 && points_per_hour < 1
? points_per_hour * hours_to_show
: 1 / points_per_hour;
const id = Math.abs(index + 1 - Math.ceil(hours_to_show * points_per_hour));
const now = this.getEndDate();
const oneMinInHours = 1 / 60;
now.setMilliseconds(now.getMilliseconds() - getMilli(offset * id + oneMinInHours));
const end = getTime(now, { hour12: !this.config.hour24 }, this._hass.language);
now.setMilliseconds(now.getMilliseconds() - getMilli(offset - oneMinInHours));
const start = getTime(now, format, this._hass.language);
this.tooltip = {
value,
id,
entity,
time: [start, end],
index,
label,
};
}
renderLabels() {
if (!this.config.show.labels || this.primaryYaxisSeries.length === 0) return;
return html`
<div class="graph__labels --primary flex">
<span class="label--max">${this.computeState(this.bound[1])}</span>
<span class="label--min">${this.computeState(this.bound[0])}</span>
</div>
`;
}
renderLabelsSecondary() {
if (!this.config.show.labels_secondary || this.secondaryYaxisSeries.length === 0) return;
return html`
<div class="graph__labels --secondary flex">
<span class="label--max">${this.computeState(this.boundSecondary[1])}</span>
<span class="label--min">${this.computeState(this.boundSecondary[0])}</span>
</div>
`;
}
renderInfo() {
const info = [];
if (this.config.show.extrema) info.push(this.min);
if (this.config.show.average) info.push(this.avg);
if (this.config.show.extrema) info.push(this.max);
if (!info.length) return;
return html`
<div class="info flex">
${info.map(entry => html`
<div class="info__item">
<span class="info__item__type">${entry.type}</span>
<span class="info__item__value">
${this.computeState(entry.state)} ${this.computeUom(0)}
</span>
<span class="info__item__time">
${entry.type !== 'avg' ? getTime(new Date(entry.last_changed), this.config.format, this._hass.language) : ''}
</span>
</div>
`)}
</div>
`;
}
handlePopup(e, entity) {
e.stopPropagation();
handleClick(this, this._hass, this.config, this.config.tap_action, entity.entity_id);
}
computeThresholds(stops, type) {
stops.sort((a, b) => b.value - a.value);
if (type === 'smooth') {
return stops;
} else {
const rect = [].concat(...stops.map((stop, i) => ([stop, {
value: stop.value - 0.0001,
color: stops[i + 1] ? stops[i + 1].color : stop.color,
}])));
return rect;
}
}
computeColor(inState, i) {
const { color_thresholds, line_color } = this.config;
const state = Number(inState) || 0;
const threshold = {
color: line_color[i] || line_color[0],
...color_thresholds.slice(-1)[0],
...color_thresholds.find(ele => ele.value < state),
};
return this.config.entities[i].color || threshold.color;
}
get visibleEntities() {
return this.config.entities.filter(entity => entity.show_graph !== false);
}
get primaryYaxisEntities() {
return this.visibleEntities.filter(entity => entity.y_axis === undefined
|| entity.y_axis === 'primary');
}
get secondaryYaxisEntities() {
return this.visibleEntities.filter(entity => entity.y_axis === 'secondary');
}
get visibleLegends() {
return this.visibleEntities.filter(entity => entity.show_legend !== false);
}
get primaryYaxisSeries() {
return this.primaryYaxisEntities.map(entity => this.Graph[entity.index]);
}
get secondaryYaxisSeries() {
return this.secondaryYaxisEntities.map(entity => this.Graph[entity.index]);
}
intColor(inState, i) {
const { color_thresholds, line_color } = this.config;
const state = Number(inState) || 0;
let intColor;
if (color_thresholds.length > 0) {
if (this.config.show.graph === 'bar') {
const { color } = color_thresholds.find(ele => ele.value < state)
|| color_thresholds.slice(-1)[0];
intColor = color;
} else {
const index = color_thresholds.findIndex(ele => ele.value < state);
const c1 = color_thresholds[index];
const c2 = color_thresholds[index - 1];
if (c2) {
const factor = (c2.value - inState) / (c2.value - c1.value);
intColor = interpolateColor(c2.color, c1.color, factor);
} else {
intColor = index
? color_thresholds[color_thresholds.length - 1].color
: color_thresholds[0].color;
}
}
}
return this.config.entities[i].color || intColor || line_color[i] || line_color[0];
}
computeName(index) {
return this.config.entities[index].name || this.entity[index].attributes.friendly_name;
}
computeIcon(entity) {
return (
this.config.icon
|| entity.attributes.icon
|| ICONS[entity.attributes.device_class]
|| ICONS.temperature
);
}
computeUom(index) {
return (
this.config.entities[index].unit
|| this.config.unit
|| this.entity[index].attributes.unit_of_measurement
|| ''
);
}
computeState(inState) {
if (this.config.state_map.length > 0) {
const stateMap = Number.isInteger(inState)
? this.config.state_map[inState]
: this.config.state_map.find(state => state.value === inState);
if (stateMap) {
return stateMap.label;
} else {
// eslint-disable-next-line no-console
console.warn(`mini-graph-card: value [${inState}] not found in state_map`);
}
}
let state;
if (typeof inState === 'string') {
state = parseFloat(inState.replace(/,/g, '.'));
} else {
state = Number(inState);
}
const dec = this.config.decimals;
if (dec === undefined || Number.isNaN(dec) || Number.isNaN(state))
return Math.round(state * 100) / 100;
const x = 10 ** dec;
return (Math.round(state * x) / x).toFixed(dec);
}
updateOnInterval() {
if (this.stateChanged && !this.updating) {
this.stateChanged = false;
this.updateData();
}
}
async updateData({ config } = this) {
this.updating = true;
const end = this.getEndDate();
const start = new Date();
start.setHours(end.getHours() - config.hours_to_show);
try {
const promise = this.entity.map((entity, i) => this.updateEntity(entity, i, start, end));
await Promise.all(promise);
} finally {
this.updating = false;
}
this.updateQueue = [];
this.bound = [
config.lower_bound !== undefined
? config.lower_bound
: Math.min(...this.primaryYaxisSeries.map(ele => ele.min)) || this.bound[0],
config.upper_bound !== undefined
? config.upper_bound
: Math.max(...this.primaryYaxisSeries.map(ele => ele.max)) || this.bound[1],
];
this.boundSecondary = [
config.lower_bound_secondary !== undefined
? config.lower_bound_secondary
: Math.min(...this.secondaryYaxisSeries.map(ele => ele.min)) || this.boundSecondary[0],
config.upper_bound_secondary !== undefined
? config.upper_bound_secondary
: Math.max(...this.secondaryYaxisSeries.map(ele => ele.max)) || this.boundSecondary[1],
];
if (config.show.graph) {
this.entity.forEach((entity, i) => {
if (!entity || this.Graph[i].coords.length === 0) return;
const bound = config.entities[i].y_axis === 'secondary' ? this.boundSecondary : this.bound;
[this.Graph[i].min, this.Graph[i].max] = [bound[0], bound[1]];
if (config.show.graph === 'bar') {
this.bar[i] = this.Graph[i].getBars(i, this.visibleEntities.length);
} else {
const line = this.Graph[i].getPath();
if (config.entities[i].show_line !== false) this.line[i] = line;
if (config.show.fill
&& config.entities[i].show_fill !== false) this.fill[i] = this.Graph[i].getFill(line);
if (config.show.points && (config.entities[i].show_points !== false)) {
this.points[i] = this.Graph[i].getPoints();
}
if (config.color_thresholds.length > 0 && !config.entities[i].color)
this.gradient[i] = this.Graph[i].computeGradient(config.color_thresholds);
}
});
this.line = [...this.line];
}
}
async getCache(key, compressed) {
const data = await localForage.getItem(key + (compressed ? '' : '-raw'));
return data ? (compressed ? decompress(data) : data) : null;
}
async setCache(key, data, compressed) {
return compressed
? localForage.setItem(key, compress(data))
: localForage.setItem(`${key}-raw`, data);
}
async updateEntity(entity, index, initStart, end) {
if (!entity
|| !this.updateQueue.includes(entity.entity_id)
|| this.config.entities[index].show_graph === false
) return;
let stateHistory = [];
let start = initStart;
let skipInitialState = false;
const history = await this.getCache(entity.entity_id, this.config.useCompress);
if (history && history.hours_to_show === this.config.hours_to_show) {
stateHistory = history.data;
let currDataIndex = stateHistory.findIndex(item => new Date(item.last_changed) > initStart);
if (currDataIndex !== -1) {
if (currDataIndex > 0) {
// include previous item
currDataIndex -= 1;
// but change it's last changed time
stateHistory[currDataIndex].last_changed = initStart;
}
stateHistory = stateHistory.slice(currDataIndex, stateHistory.length);
// skip initial state when fetching recent/not-cached data
skipInitialState = true;
} else {
// there were no states which could be used in current graph so clearing
stateHistory = [];
}
const lastFetched = new Date(history.last_fetched);
if (lastFetched > start) {
start = new Date(lastFetched - 1);
}
}
let newStateHistory = await this.fetchRecent(entity.entity_id, start, end, skipInitialState);
if (newStateHistory[0] && newStateHistory[0].length > 0) {
// check if we should convert states to numeric values
if (this.config.state_map.length > 0) {
newStateHistory[0].forEach(item => this._convertState(item));
}
newStateHistory = newStateHistory[0].filter(item => !Number.isNaN(parseFloat(item.state)));
newStateHistory = newStateHistory.map(item => ({
last_changed: item.last_changed,
state: item.state,
}));
stateHistory = [...stateHistory, ...newStateHistory];
this
.setCache(entity.entity_id, {
hours_to_show: this.config.hours_to_show,
last_fetched: end,
data: stateHistory,
}, this.config.useCompress)
.catch((err) => {
// eslint-disable-next-line no-console
console.warn('mini-graph-card: Failed to cache: ', err);
localForage.clear();
});
}
if (stateHistory.length === 0) return;
if (entity.entity_id === this.entity[0].entity_id) {
this.min = {
type: 'min',
...getMin(stateHistory, 'state'),
};
this.avg = {
type: 'avg',
state: getAvg(stateHistory, 'state'),
};
this.max = {
type: 'max',
...getMax(stateHistory, 'state'),
};
}
if (this.config.entities[index].fixed_value === true) {
const last = stateHistory[stateHistory.length - 1];
this.Graph[index].update([last, last]);
} else {
this.Graph[index].update(stateHistory);
}
}
async fetchRecent(entityId, start, end, skipInitialState) {
let url = 'history/period';
if (start) url += `/${start.toISOString()}`;
url += `?filter_entity_id=${entityId}`;
if (end) url += `&end_time=${end.toISOString()}`;
if (skipInitialState) url += '&skip_initial_state';
return this._hass.callApi('GET', url);
}
_convertState(res) {
const resultIndex = this.config.state_map.findIndex(s => s.value === res.state);
if (resultIndex === -1) {
return;
}
res.state = resultIndex;
}
getEndDate() {
const date = new Date();
switch (this.config.group_by) {
case 'date':
date.setDate(date.getDate() + 1);
date.setHours(0, 0);
break;
case 'hour':
date.setHours(date.getHours() + 1);
date.setMinutes(0, 0);
break;
default:
break;
}
return date;
}
getCardSize() {
return 3;
}
}
customElements.define('mini-graph-card', MiniGraphCard);