type: custom:stack-in-card
card_mod:
style: |
ha-card {
border: 2px solid #0097E0;
border-radius: 16px;
background: var(--ha-card-background, var(--card-background-color, #FFFFFF));
box-shadow: 0 8px 24px rgba(0, 151, 224, 0.18);
overflow: visible;
}
cards:
# --- HEADER: the same for every Daikin Cycle ML card (#427) ---
- type: custom:button-card
variables: &dcm
lang_override: '' # '' = auto (HA language, then integration language) | en | nl | fr
theme_override: auto # auto (follows the HA dark mode) | light | dark
show_help: true # false = hide the explanation notes
show_name: false
show_icon: false
triggers_update: all
styles:
card:
- background: none
- box-shadow: none
- border: none
- border-radius: 14px 14px 0 0
- padding: 0
grid:
- grid-template-areas: '"content"'
- grid-template-columns: 1fr
custom_fields:
content:
- width: 100%
custom_fields:
content: |
[[[
/* DCM-COMMON-BEGIN (#427) shared by every Daikin Cycle ML card: language, theme, header.
Do not edit in a card: edit tools/card_common.js and run tools/sync_card_common.py */
var DCM = (function () {
var V = (typeof variables !== 'undefined' && variables) ? variables : {};
var H = (typeof hass !== 'undefined' && hass) ? hass : {};
var S = (typeof states !== 'undefined' && states) ? states : {};
var find = function (tk, sfx) {
var ids = Object.keys(S), i, j, k, E = H.entities || {};
for (i = 0; i < ids.length; i++) {
if (ids[i].indexOf('sensor.') !== 0) continue;
for (j = 0; j < sfx.length; j++) { if (ids[i].slice(-sfx[j].length - 1) === '_' + sfx[j]) return ids[i]; }
}
for (k in E) { if (E[k] && E[k].platform === 'daikin_cycle_ml' && E[k].translation_key === tk && S[k]) return k; }
return null;
};
var A = function (id) { return (id && S[id] && S[id].attributes) ? S[id].attributes : {}; };
var csA = A(find('cycle_state', ['cycle_state', 'cyclus_status', 'etat_du_cycle']));
var spA = A(find('hp_specs', ['hp_specs', 'wp_specs', 'caracteristiques_de_la_pac']));
/* language: lang_override, then the HA language, then the integration language, then English */
var LS = ['en', 'nl', 'fr'];
var ov = String(V.lang_override || '').toLowerCase();
var ha = String(H.language || '').toLowerCase().slice(0, 2);
var cl = String(csA.configured_language || '').toLowerCase();
var lang = LS.indexOf(ov) >= 0 ? ov : (LS.indexOf(ha) >= 0 ? ha : (LS.indexOf(cl) >= 0 ? cl : 'en'));
/* theme: auto follows the HA dark mode; light / dark force it */
var th = String(V.theme_override || 'auto').toLowerCase();
var dark = th === 'dark' ? true : (th === 'light' ? false : !!(H.themes && H.themes.darkMode));
var P = dark
? { bg: '#1B1F24', bg2: '#232A33', bg3: '#1E3448', hd1: '#1E3448', hd2: '#15283A', text: '#E6F0FA', text2: '#90CAF9',
muted: '#B0BEC5', border: 'rgba(79,195,247,0.35)', accent: '#4FC3F7', good: '#66BB6A', warn: '#FFA726', bad: '#EF5350' }
: { bg: '#FFFFFF', bg2: '#F5FAFD', bg3: '#E3F2FD', hd1: '#E3F2FD', hd2: '#BBDEFB', text: '#0D47A1', text2: '#1565C0',
muted: '#546E7A', border: 'rgba(0,151,224,0.25)', accent: '#0097E0', good: '#2E7D32', warn: '#E65100', bad: '#C62828' };
/* light colours of the cards -> dark mode (light backgrounds dark, dark text light) */
var MAP = {
'#FFFFFF': P.bg, '#F5FAFD': P.bg2, '#F5FAFE': P.bg2, '#E6F4FB': P.bg2, '#E8F2FB': P.bg2, '#EAF2F8': P.bg2,
'#E3F2FD': P.bg3, '#D6ECF7': P.bg3, '#DCEBFA': P.bg3, '#BBDEFB': '#1F4A6B', '#D6EAF8': P.bg3, '#E1F5FE': P.bg3, '#AED6F1': '#1F4A6B',
'#FFF3E0': '#3A2A12', '#FFF8EC': '#3A2A12', '#FDEAD0': '#3A2A12', '#FFEBEE': '#3A1D1D', '#FDECEA': '#3A1D1D', '#FBD0C8': '#3A1D1D',
'#E8F5E9': '#1C3324', '#EAFAF1': '#1C3324', '#D5F5E3': '#1C3324', '#F3E5F5': '#2E2236',
'#0D47A1': P.text, '#003366': P.text, '#001B3D': P.text, '#003A70': P.text, '#00539F': '#BBDEFB', '#005A9C': '#BBDEFB',
'#1565C0': P.text2, '#1976D2': '#64B5F6', '#546E7A': P.muted, '#5D6D7E': P.muted, '#7F8C8D': '#9EADB5', '#95A5A6': '#9EADB5',
'#37474F': '#CFD8DC', '#444444': '#CFD8DC', '#000000': '#ECEFF1', '#94A3B8': '#78909C', '#6A1B9A': '#CE93D8',
'#2E7D32': '#4CAF50', '#1E8449': '#81C784', '#C62828': '#E53935', '#E65100': '#FB8C00', '#7D4F00': '#FFCC80',
'#8B1A1A': '#EF9A9A', '#7A0008': '#EF9A9A'
};
var paint = function (html) {
if (!dark || typeof html !== 'string') return html;
return html
.replace(/(background(?:-color)?\s*:\s*)(#fff\b|white\b)/gi, '$1' + P.bg)
.replace(/(<(?:rect|circle|ellipse|path)\b[^>]*?\sfill=")(white|#fff|#ffffff)(")/gi, '$1' + P.bg2 + '$3')
.replace(/rgba\(\s*255\s*,\s*255\s*,\s*255\s*,\s*([0-9.]+)\s*\)/g, function (m, a) { return 'rgba(255,255,255,' + Math.min(0.08, parseFloat(a) * 0.1).toFixed(3) + ')'; })
.replace(/#[0-9a-fA-F]{6}\b/g, function (m) { return MAP[m.toUpperCase()] || m; });
};
var T3 = function (o) { return (o && typeof o === 'object') ? (o[lang] || o.en || '') : String(o || ''); };
var model = spA.model ? String(spA.model).toUpperCase() : '';
var meta = [spA.family, spA.kw ? spA.kw + ' kW' : '', spA.refrigerant].filter(function (x) { return x && String(x) !== 'None'; }).join(' · ');
/* one header for every card: icon, title + model, subtitle + family / kW / refrigerant */
var header = function (icon, title, sub) {
return '
';
};
return { lang: lang, dark: dark, P: P, paint: paint, header: header, T3: T3, V: V, model: model,
showHelp: V.show_help !== false && V.show_hints !== false };
})();
/* DCM-COMMON-END */
return DCM.header("📅",
{en: "Summary", nl: "Samenvatting", fr: "Résumé"},
{en: "Cycles · duration · quality · events", nl: "Cycli · duur · kwaliteit · events", fr: "Cycles · durée · qualité · événements"});
]]]
- type: custom:button-card
variables: *dcm
show_name: false
show_icon: false
styles:
grid:
- grid-template-areas: '"content"'
- grid-template-columns: 1fr
card:
- background: none
- box-shadow: none
- border: none
- padding: 10px 10px 8px 10px
- overflow: visible
- white-space: normal !important
custom_fields:
content:
- width: 100%
- white-space: normal !important
custom_fields:
content: |
[[[
/* DCM-COMMON-BEGIN (#427) shared by every Daikin Cycle ML card: language, theme, header.
Do not edit in a card: edit tools/card_common.js and run tools/sync_card_common.py */
var DCM = (function () {
var V = (typeof variables !== 'undefined' && variables) ? variables : {};
var H = (typeof hass !== 'undefined' && hass) ? hass : {};
var S = (typeof states !== 'undefined' && states) ? states : {};
var find = function (tk, sfx) {
var ids = Object.keys(S), i, j, k, E = H.entities || {};
for (i = 0; i < ids.length; i++) {
if (ids[i].indexOf('sensor.') !== 0) continue;
for (j = 0; j < sfx.length; j++) { if (ids[i].slice(-sfx[j].length - 1) === '_' + sfx[j]) return ids[i]; }
}
for (k in E) { if (E[k] && E[k].platform === 'daikin_cycle_ml' && E[k].translation_key === tk && S[k]) return k; }
return null;
};
var A = function (id) { return (id && S[id] && S[id].attributes) ? S[id].attributes : {}; };
var csA = A(find('cycle_state', ['cycle_state', 'cyclus_status', 'etat_du_cycle']));
var spA = A(find('hp_specs', ['hp_specs', 'wp_specs', 'caracteristiques_de_la_pac']));
/* language: lang_override, then the HA language, then the integration language, then English */
var LS = ['en', 'nl', 'fr'];
var ov = String(V.lang_override || '').toLowerCase();
var ha = String(H.language || '').toLowerCase().slice(0, 2);
var cl = String(csA.configured_language || '').toLowerCase();
var lang = LS.indexOf(ov) >= 0 ? ov : (LS.indexOf(ha) >= 0 ? ha : (LS.indexOf(cl) >= 0 ? cl : 'en'));
/* theme: auto follows the HA dark mode; light / dark force it */
var th = String(V.theme_override || 'auto').toLowerCase();
var dark = th === 'dark' ? true : (th === 'light' ? false : !!(H.themes && H.themes.darkMode));
var P = dark
? { bg: '#1B1F24', bg2: '#232A33', bg3: '#1E3448', hd1: '#1E3448', hd2: '#15283A', text: '#E6F0FA', text2: '#90CAF9',
muted: '#B0BEC5', border: 'rgba(79,195,247,0.35)', accent: '#4FC3F7', good: '#66BB6A', warn: '#FFA726', bad: '#EF5350' }
: { bg: '#FFFFFF', bg2: '#F5FAFD', bg3: '#E3F2FD', hd1: '#E3F2FD', hd2: '#BBDEFB', text: '#0D47A1', text2: '#1565C0',
muted: '#546E7A', border: 'rgba(0,151,224,0.25)', accent: '#0097E0', good: '#2E7D32', warn: '#E65100', bad: '#C62828' };
/* light colours of the cards -> dark mode (light backgrounds dark, dark text light) */
var MAP = {
'#FFFFFF': P.bg, '#F5FAFD': P.bg2, '#F5FAFE': P.bg2, '#E6F4FB': P.bg2, '#E8F2FB': P.bg2, '#EAF2F8': P.bg2,
'#E3F2FD': P.bg3, '#D6ECF7': P.bg3, '#DCEBFA': P.bg3, '#BBDEFB': '#1F4A6B', '#D6EAF8': P.bg3, '#E1F5FE': P.bg3, '#AED6F1': '#1F4A6B',
'#FFF3E0': '#3A2A12', '#FFF8EC': '#3A2A12', '#FDEAD0': '#3A2A12', '#FFEBEE': '#3A1D1D', '#FDECEA': '#3A1D1D', '#FBD0C8': '#3A1D1D',
'#E8F5E9': '#1C3324', '#EAFAF1': '#1C3324', '#D5F5E3': '#1C3324', '#F3E5F5': '#2E2236',
'#0D47A1': P.text, '#003366': P.text, '#001B3D': P.text, '#003A70': P.text, '#00539F': '#BBDEFB', '#005A9C': '#BBDEFB',
'#1565C0': P.text2, '#1976D2': '#64B5F6', '#546E7A': P.muted, '#5D6D7E': P.muted, '#7F8C8D': '#9EADB5', '#95A5A6': '#9EADB5',
'#37474F': '#CFD8DC', '#444444': '#CFD8DC', '#000000': '#ECEFF1', '#94A3B8': '#78909C', '#6A1B9A': '#CE93D8',
'#2E7D32': '#4CAF50', '#1E8449': '#81C784', '#C62828': '#E53935', '#E65100': '#FB8C00', '#7D4F00': '#FFCC80',
'#8B1A1A': '#EF9A9A', '#7A0008': '#EF9A9A'
};
var paint = function (html) {
if (!dark || typeof html !== 'string') return html;
return html
.replace(/(background(?:-color)?\s*:\s*)(#fff\b|white\b)/gi, '$1' + P.bg)
.replace(/(<(?:rect|circle|ellipse|path)\b[^>]*?\sfill=")(white|#fff|#ffffff)(")/gi, '$1' + P.bg2 + '$3')
.replace(/rgba\(\s*255\s*,\s*255\s*,\s*255\s*,\s*([0-9.]+)\s*\)/g, function (m, a) { return 'rgba(255,255,255,' + Math.min(0.08, parseFloat(a) * 0.1).toFixed(3) + ')'; })
.replace(/#[0-9a-fA-F]{6}\b/g, function (m) { return MAP[m.toUpperCase()] || m; });
};
var T3 = function (o) { return (o && typeof o === 'object') ? (o[lang] || o.en || '') : String(o || ''); };
var model = spA.model ? String(spA.model).toUpperCase() : '';
var meta = [spA.family, spA.kw ? spA.kw + ' kW' : '', spA.refrigerant].filter(function (x) { return x && String(x) !== 'None'; }).join(' · ');
/* one header for every card: icon, title + model, subtitle + family / kW / refrigerant */
var header = function (icon, title, sub) {
return '';
};
return { lang: lang, dark: dark, P: P, paint: paint, header: header, T3: T3, V: V, model: model,
showHelp: V.show_help !== false && V.show_hints !== false };
})();
/* DCM-COMMON-END */
return DCM.paint((function () {
var _DEC = (function(){ try { var _lc = (typeof hass !== 'undefined' && hass && hass.locale) ? hass.locale : {}; var _nf = _lc.number_format; if (_nf === 'comma_decimal' || _nf === 'none') return '.'; if (_nf === 'decimal_comma' || _nf === 'space_comma') return ','; var _l = String(_lc.language || (typeof hass !== 'undefined' && hass && hass.language) || 'en'); return (1.5).toLocaleString(_l).indexOf(',') >= 0 ? ',' : '.'; } catch (e) { return '.'; } })(); /* #427: decimal separator from the HA number format */
/* #347 entity resolver (EN id -> [translation_key, nl, fr]) */
var _dcmA = {"sensor.daikin_cycle_ml_daily_summary_recent":["daily_summary_recent","daikin_cycle_ml_recent_dagoverzicht","daikin_cycle_ml_resume_des_derniers_jours"],"sensor.daikin_cycle_ml_hp_specs":["hp_specs","daikin_cycle_ml_wp_specs","daikin_cycle_ml_caracteristiques_de_la_pac"]};
var _dcmC = {};
var _dcmR = function(id){ if (_dcmC[id]) return _dcmC[id]; var r = id, a = _dcmA[id], st = (typeof states !== 'undefined' && states) ? states : {}; if (!st[id] && a) { var dom = id.split('.')[0], i, k, ents = (typeof hass !== 'undefined' && hass && hass.entities) ? hass.entities : null; if (ents) { for (k in ents) { var e = ents[k]; if (e && e.platform === 'daikin_cycle_ml' && e.translation_key === a[0] && k.indexOf(dom + '.') === 0 && st[k]) { r = k; break; } } } if (r === id) { for (i = 1; i < a.length; i++) { if (st[dom + '.' + a[i]]) { r = dom + '.' + a[i]; break; } } } } _dcmC[id] = r; return r; };
try {
/* ============================================================
LANGUAGE
============================================================ */
var LANG = DCM.lang; /* #427: lang_override, HA language, integration language */
/* ============================================================
i18n
============================================================ */
var STR = {
nl: {
summary: 'SAMENVATTING', days: 'dagen', cycles: 'cycli',
quality: 'KWAL', heating: 'Verwarming', dhw: 'DHW', cooling: 'Koeling',
best_day: 'Beste dag', worst_day: 'Slechtste dag',
sparklines: 'Trends', quality_chart: 'Kwaliteit per dag',
cycles_chart: 'Cycli per dag', duration_chart: 'Duur per dag',
events_chart: 'Events per dag', events: 'Events',
clipped: 'geclipt', total: 'totaal', cap: 'max',
today: 'vandaag', yesterday: 'gisteren', days_ago: 'd geleden',
future: 'toekomst', no_data: 'Geen data',
legend_heat: 'Verwarming', legend_dhw: 'DHW',
legend_cool: 'Koeling', legend_gem_line: 'gem',
legend_buh: 'BUH', legend_defrost: 'Defrost',
outlier_warn: 'dag >24u — check data',
threshold_legend: 'drempel',
tooltip_heating: 'Verwarming', tooltip_dhw: 'DHW',
tooltip_cooling: 'Koeling', tooltip_buh: 'BUH',
tooltip_defrost: 'Defrost',
avg: 'gem', spark_quality: 'Kwaliteit',
spark_cycles: 'Cycli/dag', spark_duration: 'Duur/dag',
q_good: 'Goed ≥70', q_mid: 'Midden 40-70', q_low: 'Laag <40',
heat_short: 'Verw.', cool_short: 'Koel', per_day_short: '/d'
},
en: {
summary: 'SUMMARY', days: 'days', cycles: 'cycles',
quality: 'QUAL', heating: 'Heating', dhw: 'DHW', cooling: 'Cooling',
best_day: 'Best day', worst_day: 'Worst day',
sparklines: 'Trends', quality_chart: 'Quality per day',
cycles_chart: 'Cycles per day', duration_chart: 'Duration per day',
events_chart: 'Events per day', events: 'Events',
clipped: 'clipped', total: 'total', cap: 'max',
today: 'today', yesterday: 'yesterday', days_ago: 'd ago',
future: 'future', no_data: 'No data',
legend_heat: 'Heating', legend_dhw: 'DHW',
legend_cool: 'Cooling', legend_gem_line: 'avg',
legend_buh: 'BUH', legend_defrost: 'Defrost',
outlier_warn: 'day >24h — check data',
threshold_legend: 'threshold',
tooltip_heating: 'Heating', tooltip_dhw: 'DHW',
tooltip_cooling: 'Cooling', tooltip_buh: 'BUH',
tooltip_defrost: 'Defrost',
avg: 'avg', spark_quality: 'Quality',
spark_cycles: 'Cycles/day', spark_duration: 'Duration/day',
q_good: 'Good ≥70', q_mid: 'Mid 40-70', q_low: 'Low <40',
heat_short: 'Heat', cool_short: 'Cool', per_day_short: '/d'
},
fr: {
summary: 'RÉSUMÉ', days: 'jours', cycles: 'cycles',
quality: 'QUAL', heating: 'Chauffage', dhw: 'ECS', cooling: 'Froid',
best_day: 'Meilleur jour', worst_day: 'Pire jour',
sparklines: 'Tendances', quality_chart: 'Qualité par jour',
cycles_chart: 'Cycles par jour', duration_chart: 'Durée par jour',
events_chart: 'Événements par jour', events: 'Événements',
clipped: 'tronqué', total: 'total', cap: 'max',
today: 'aujourd\'hui', yesterday: 'hier', days_ago: ' j avant',
future: 'futur', no_data: 'Pas de données',
legend_heat: 'Chauffage', legend_dhw: 'ECS',
legend_cool: 'Froid', legend_gem_line: 'moy.',
legend_buh: 'Appoint', legend_defrost: 'Dégivrage',
outlier_warn: 'jour >24 h — vérifier les données',
threshold_legend: 'seuil',
tooltip_heating: 'Chauffage', tooltip_dhw: 'ECS',
tooltip_cooling: 'Froid', tooltip_buh: 'Appoint',
tooltip_defrost: 'Dégivrage',
avg: 'moy.', spark_quality: 'Qualité',
spark_cycles: 'Cycles/jour', spark_duration: 'Durée/jour',
q_good: 'Bon ≥70', q_mid: 'Moyen 40-70', q_low: 'Faible <40',
heat_short: 'Chauf.', cool_short: 'Froid', per_day_short: '/j'
}
};
var t = function(k){ return (STR[LANG] && STR[LANG][k]) || (STR.en && STR.en[k]) || k; };
var locale = LANG === 'nl' ? 'nl-NL' : (LANG === 'fr' ? 'fr-FR' : 'en-GB');
/* ============================================================
COLORS
============================================================ */
var C = {
heating: '#E63946', dhw: '#4FC3F7', cooling: '#0D47A1',
buh: '#E65100', defrost: '#1976D2', quality: '#2E7D32',
gem: '#6A1B9A'
};
var CBG = {
heating: '#FFEBEE', dhw: '#E1F5FE', cooling: '#E3F2FD',
buh: '#FFF3E0', defrost: '#E3F2FD', quality: '#E8F5E9',
gem: '#F3E5F5'
};
/* Quality band colors */
var QGOOD = '#2E7D32';
var QMID = '#E65100';
var QLOW = '#C62828';
/* ============================================================
HELPERS
============================================================ */
var stStr = function(s,d){ if(d===undefined)d='—'; var x=states[s]; if(!x||!x.state)return d; if(x.state==='unknown'||x.state==='unavailable'||x.state==='none'||x.state==='')return d; return x.state; };
var hasV = function(v){ return v!==null && v!==undefined && v!=='' && String(v)!=='None' && String(v)!=='unknown' && String(v)!=='unavailable'; };
var v1 = function(v){ if(!hasV(v)||isNaN(parseFloat(v))||!isFinite(parseFloat(v)))return '—'; return Number(v).toFixed(1).replace('.', _DEC); };
var v2 = function(v){ if(!hasV(v)||isNaN(parseFloat(v))||!isFinite(parseFloat(v)))return '—'; return Number(v).toFixed(2).replace('.', _DEC); };
var vI = function(v){ if(!hasV(v)||isNaN(parseFloat(v)))return '—'; return Math.round(parseFloat(v)).toString(); };
var attr = function(id,n,d){ try{ var a=states[id] && states[id].attributes; if(!a)return d; var v=a[n]; if(v===undefined||v===null||String(v)==='None')return d; return v; } catch(e){ return d; } };
var aN = function(id,n,d){ var v=attr(id,n,null); if(v===null)return d; var x=parseFloat(v); return isNaN(x)?d:x; };
var fmtBigNum = function(v){
if(!hasV(v)||isNaN(parseFloat(v))) return '—';
var n = Number(v); var neg = n < 0; n = Math.abs(n); var s;
if(n >= 1000000) s = (n/1000000).toFixed(1).replace('.', _DEC)+'M';
else if(n >= 10000) s = Math.round(n/1000)+'k';
else if(n >= 1000) s = (n/1000).toFixed(1).replace('.', _DEC)+'k';
else s = String(Math.round(n));
return neg ? '-'+s : s;
};
var fmtBigHours = function(h){
if(!hasV(h)||isNaN(parseFloat(h))) return '—';
var n = Number(h);
if(n >= 24*7) return Math.round(n/24)+'d';
if(n >= 24) return Math.round(n)+'h';
if(n >= 10) return n.toFixed(0)+'h';
if(n >= 1) return n.toFixed(1).replace('.', _DEC)+'h';
return Math.round(n*60)+'m';
};
var fmtBigMin = function(m){
if(!hasV(m)||isNaN(parseFloat(m))) return '—';
var n = Number(m);
if(n >= 1440) return Math.round(n/1440)+'d';
if(n >= 120) return Math.round(n/60)+'h';
if(n >= 60) return (n/60).toFixed(1).replace('.', _DEC)+'h';
return Math.round(n)+'m';
};
var weekday = function(iso){
if(!iso) return '';
try{ var d = new Date(iso + 'T12:00:00'); return d.toLocaleDateString(locale, {weekday:'short'}); }
catch(e){ return ''; }
};
var shortDate = function(iso){
if(!iso) return '—';
try{ var d = new Date(iso + 'T12:00:00'); return d.toLocaleDateString(locale, {day:'numeric', month:'short'}); }
catch(e){ return iso; }
};
var fmtDay = function(iso){
if(!iso) return '—';
try{ var d = new Date(iso + 'T12:00:00'); return d.toLocaleDateString(locale, {day:'2-digit', month:'2-digit'}); }
catch(e){ var p=String(iso).split('-'); return p.length>=3 ? p[2]+'/'+p[1] : iso; }
};
var relDays = function(iso){
if(!iso) return '';
try{
var d = new Date(iso + 'T12:00:00');
var today = new Date(); today.setHours(12,0,0,0);
var diff = Math.round((today - d) / 86400000);
if(diff === 0) return t('today');
if(diff === 1) return t('yesterday');
if(diff < 0) return t('future');
return diff + t('days_ago');
}catch(e){ return ''; }
};
var qColor = function(q){ return q===null||q===undefined?'#546E7A':(q>=70?QGOOD:q>=40?QMID:QLOW); };
var roundNice = function(v){
if(v <= 0) return 1;
var mag = Math.pow(10, Math.floor(Math.log10(v)));
var norm = v / mag; var nice;
if(norm <= 1) nice = 1;
else if(norm <= 2) nice = 2;
else if(norm <= 5) nice = 5;
else nice = 10;
return nice * mag;
};
/* ============================================================
READ
============================================================ */
var SUMMARY = _dcmR('sensor.daikin_cycle_ml_daily_summary_recent');
var SPECS = _dcmR('sensor.daikin_cycle_ml_hp_specs');
var totalCycles = parseInt(stStr(SUMMARY, '0'), 10) || 0;
var daysAvail = aN(SUMMARY, 'days_available', 0);
var latestDay = attr(SUMMARY, 'latest_day', null);
var oldestDay = attr(SUMMARY, 'oldest_day', null);
var rawDays = attr(SUMMARY, 'days', []);
var totals = attr(SUMMARY, 'totals_by_mode', {});
/* HP specs (for hero only) */
var specModel = attr(SPECS, 'model', null);
var specFamily = attr(SPECS, 'family', null);
var specKw = aN(SPECS, 'kw', null);
/* ============================================================
GROUP BY DATE
============================================================ */
var byDate = {};
for(var ri = 0; ri < rawDays.length; ri++){
var rd = rawDays[ri];
var dayKey = rd.day;
if(!dayKey) continue;
if(!byDate[dayKey]){
byDate[dayKey] = {
day: dayKey, cycles: 0, dur_min: 0, dur_max: 0,
quality_sum: 0, quality_n: 0,
buh: 0, defrost: 0,
modes: { heating:{cycles:0,dur:0}, dhw:{cycles:0,dur:0}, cooling:{cycles:0,dur:0} }
};
}
var e = byDate[dayKey];
e.cycles += (rd.cycles || 0);
e.dur_min += (rd.dur_min || 0);
if(hasV(rd.dur_max) && parseFloat(rd.dur_max) > e.dur_max) e.dur_max = parseFloat(rd.dur_max);
if(hasV(rd.quality_avg)){
e.quality_sum += parseFloat(rd.quality_avg);
e.quality_n += 1;
}
e.buh += (rd.buh || 0);
e.defrost += (rd.defrost || 0);
var mkey = rd.mode || 'unknown';
if(e.modes[mkey]){
e.modes[mkey].cycles += (rd.cycles || 0);
e.modes[mkey].dur += (rd.dur_min || 0);
}
}
/* #427: real per-day defrost events / BUH use (runtime_acc, #400),
the same source as the Today block; cycle counts stay the fallback */
var _evByDay = {};
try { _evByDay = (states[SUMMARY] && states[SUMMARY].attributes && states[SUMMARY].attributes.events_by_day) || {}; } catch (e) {}
var daysArr = Object.keys(byDate).map(function(k){
var e = byDate[k];
e.quality_avg = e.quality_n > 0 ? e.quality_sum / e.quality_n : null;
var evD = _evByDay[e.day];
if (evD) {
if (hasV(evD.defrost_events) && parseFloat(evD.defrost_events) > e.defrost) e.defrost = parseFloat(evD.defrost_events);
if (hasV(evD.buh_min) && parseFloat(evD.buh_min) > 0 && e.buh < 1) e.buh = 1;
}
return e;
}).sort(function(a,b){ return a.day < b.day ? -1 : 1; });
/* ============================================================
TOTALS
============================================================ */
var heating = totals.heating || {days:0, cycles:0, dur_min:0, buh:0, defrost:0};
var dhw = totals.dhw || {days:0, cycles:0, dur_min:0, buh:0, defrost:0};
var cooling = totals.cooling || {days:0, cycles:0, dur_min:0, buh:0, defrost:0};
var qualityVals = daysArr.filter(function(d){ return d.quality_avg !== null; }).map(function(d){ return d.quality_avg; });
var avgQuality = qualityVals.length > 0 ? qualityVals.reduce(function(a,v){ return a+v; }, 0) / qualityVals.length : null;
var totalHours = daysArr.reduce(function(a,d){ return a + d.dur_min; }, 0) / 60;
var totalBuh = daysArr.reduce(function(a,d){ return a + d.buh; }, 0);
var totalDefrost = daysArr.reduce(function(a,d){ return a + d.defrost; }, 0);
var qColorAll = qColor(avgQuality);
var hasCooling = (cooling.cycles > 0);
var hasDHW = (dhw.cycles > 0);
var hasBuh = (totalBuh > 0);
var hasDefrost = (totalDefrost > 0);
var hasHeating = (heating.cycles > 0);
var hasQuality = (qualityVals.length > 0);
var outlierDays = daysArr.filter(function(d){ return d.dur_min > 1440; });
var hasOutliers = outlierDays.length > 0;
var realDurations = daysArr.filter(function(d){ return d.dur_min > 0 && d.dur_min <= 1440; })
.map(function(d){ return d.dur_min / 60; })
.sort(function(a,b){ return a-b; });
var p95 = realDurations.length > 0 ? realDurations[Math.floor(realDurations.length * 0.95)] : 4;
var maxReal = realDurations.length > 0 ? realDurations[realDurations.length-1] : 4;
var c2Cap = Math.max(4, Math.min(24, roundNice(Math.max(p95 * 1.15, 4))));
if(maxReal <= 24 && maxReal <= c2Cap * 1.3) c2Cap = Math.max(4, Math.ceil(maxReal));
/* ============================================================
INSIGHTS
============================================================ */
var byQuality = daysArr.filter(function(d){ return d.quality_avg !== null; })
.slice().sort(function(a,b){ return b.quality_avg - a.quality_avg; });
var bestDay = byQuality.length > 0 ? byQuality[0] : null;
var worstDay = byQuality.length > 1 ? byQuality[byQuality.length-1] : null;
var avgCyclesPerDay = daysArr.length > 0 ? totalCycles / daysArr.length : null;
var avgRuntimePerDay = daysArr.length > 0 ? totalHours / daysArr.length : null;
var avgCycleDur = totalCycles > 0 ? (totalHours * 60) / totalCycles : null;
var buhRate = totalCycles > 0 ? (totalBuh / totalCycles * 100) : null;
var defrostRate = totalCycles > 0 ? (totalDefrost / totalCycles * 100) : null;
var half = Math.floor(daysArr.length / 2);
var avgQ = function(arr){
var q = arr.filter(function(d){ return d.quality_avg !== null; });
return q.length > 0 ? q.reduce(function(a,d){ return a + d.quality_avg; }, 0) / q.length : null;
};
var qFirst = avgQ(daysArr.slice(0, half));
var qSecond = avgQ(daysArr.slice(half));
var trendDiff = (qFirst !== null && qSecond !== null) ? (qSecond - qFirst) : null;
var qualityTrend = 'flat';
if(trendDiff !== null){
if(trendDiff > 5) qualityTrend = 'up';
else if(trendDiff < -5) qualityTrend = 'down';
}
var trendColor = qualityTrend==='up'?QGOOD:qualityTrend==='down'?QLOW:'#546E7A';
var trendIcon = qualityTrend==='up'?'📈':qualityTrend==='down'?'📉':'➡️';
var buhRateColor = buhRate===null?'#546E7A':(buhRate<=10?QGOOD:buhRate<=25?QMID:QLOW);
var defrostRateColor = defrostRate===null?'#546E7A':(defrostRate<=15?QGOOD:defrostRate<=35?QMID:QLOW);
/* ============================================================
CHART DIMENSIONS
============================================================ */
var numDays = daysArr.length;
var chartW = 500;
var c1H = 200;
var c2H = 185;
var qcH = 145; /* quality chart height */
var plotBase = chartW - 80;
var c1BarW = Math.max(3, Math.min(40, (plotBase / Math.max(1, numDays)) * 0.6));
var c2BarW = c1BarW;
var c1MaxRaw = Math.max.apply(null, daysArr.map(function(d){ return d.cycles; }));
if(!isFinite(c1MaxRaw) || c1MaxRaw < 1) c1MaxRaw = 1;
var c1Max = roundNice(c1MaxRaw);
var c1PadL = Math.max(34, 20 + String(Math.round(c1Max)).length * 8);
var c2PadL = Math.max(40, 26 + String(Math.round(c2Cap)).length * 8);
var labelEvery = 1;
if(numDays > 14) labelEvery = 2;
if(numDays > 30) labelEvery = 3;
if(numDays > 45) labelEvery = 5;
if(numDays > 60) labelEvery = 7;
var showDateLabel = numDays <= 21;
/* ============================================================
SPARKLINES (COMPACT)
============================================================ */
var sparkW = 500, sparkH = 62;
var panW = 155, panGap = 17;
var panH = 36;
var panPadL = 4, panPadR = 4, panPadT = 18, panPadB = 4;
var sparkData = [
{ title: t('spark_quality'), color: C.quality, bg: CBG.quality,
data: daysArr.map(function(d){ return d.quality_avg; }),
yMin: 0, yMax: 100,
fmt: function(v){ return Math.round(v)+'%'; } },
{ title: t('spark_cycles'), color: C.heating, bg: CBG.heating,
data: daysArr.map(function(d){ return d.cycles; }),
yMin: 0, yMax: null,
fmt: function(v){ return String(Math.round(v)); } },
{ title: t('spark_duration'), color: C.cooling, bg: CBG.cooling,
data: daysArr.map(function(d){ return d.dur_min / 60; }),
yMin: 0, yMax: null,
fmt: function(v){ return v < 10 ? v.toFixed(1).replace('.', _DEC)+'h' : Math.round(v)+'h'; } }
];
var spark = '';
/* ============================================================
QUALITY PER DAY CHART (dynamic colors)
============================================================ */
var qcPadL = 34, qcPadR = 12, qcPadT = 24, qcPadB = showDateLabel ? 52 : 40;
var qcPlotW = chartW - qcPadL - qcPadR;
var qcPlotH = qcH - qcPadT - qcPadB;
var qcSlot = qcPlotW / Math.max(1, numDays);
var qcx = function(i){ return qcPadL + i * qcSlot + qcSlot/2; };
var qcy = function(v){ return qcPadT + qcPlotH - (Math.max(0,Math.min(100,v)) / 100) * qcPlotH; };
var qc = '';
/* ============================================================
CYCLES CHART
============================================================ */
var c1PadR = 12, c1PadT = 24, c1PadB = showDateLabel ? 52 : 40;
var c1PlotW = chartW - c1PadL - c1PadR;
var c1PlotH = c1H - c1PadT - c1PadB;
var c1Slot = c1PlotW / Math.max(1, numDays);
var c1x = function(i){ return c1PadL + i * c1Slot + (c1Slot - c1BarW)/2; };
var c1y = function(v){ return c1PadT + c1PlotH - (v / c1Max) * c1PlotH; };
var c1StepCount = Math.min(5, c1Max);
var c1StepVal = c1Max / c1StepCount;
var c1 = '';
/* ============================================================
DURATION CHART
============================================================ */
var c2PadR = 12, c2PadT = 24, c2PadB = showDateLabel ? 52 : 40;
var c2PlotW = chartW - c2PadL - c2PadR;
var c2PlotH = c2H - c2PadT - c2PadB;
var c2MaxH = c2Cap;
var c2Slot = c2PlotW / Math.max(1, numDays);
var c2x = function(i){ return c2PadL + i * c2Slot + (c2Slot - c2BarW)/2; };
var c2y = function(v){ return c2PadT + c2PlotH - (Math.min(v, c2MaxH) / c2MaxH) * c2PlotH; };
var c2StepCount = 4;
var c2StepVal = c2MaxH / c2StepCount;
var c2 = '';
/* ============================================================
EVENT STRIP
============================================================ */
var showBuhRow = hasBuh;
var showDefrostRow = hasDefrost;
var stRows = (showBuhRow ? 1 : 0) + (showDefrostRow ? 1 : 0);
var stW = chartW;
var stPadL = Math.max(56, 26 + 24);
var stPadR = 12;
var stPlotW = stW - stPadL - stPadR;
var stSlot = stPlotW / Math.max(1, numDays);
var stRowH = 24;
var stPadT = 8;
var stPadB = showDateLabel ? 32 : 20;
var stH = stPadT + Math.max(1, stRows) * stRowH + stPadB;
var strip = '';
/* ============================================================
CHIP HELPERS
============================================================ */
var chip = function(color, bg, label, title){
var tt = title ? ' title="'+title+'"' : '';
return ''
+ ''
+ label + '';
};
var chipRow = function(arr, extra){
var s = '';
for(var ci = 0; ci < arr.length; ci++){
s += chip(arr[ci].col, arr[ci].bg, arr[ci].label, arr[ci].title);
}
if(extra){
s += ''+extra+'';
}
s += '
';
return s;
};
/* ============================================================
RENDER
============================================================ */
var r = '';
r += '';
/* ===== HERO ===== */
r += '
';
r += '
';
r += '
';
r += '
🌡️
';
r += '
';
r += '
DAIKIN CYCLE ML
';
r += '
'+(specModel?specModel.toUpperCase():'—')+'
';
r += '
'+(specFamily||'—')+(specKw?' · '+vI(specKw)+' kW':'')+'
';
r += '
';
r += '
';
r += '
'+t('quality')+'
';
r += '
'+(avgQuality===null?'—':vI(avgQuality)+'%')+'
';
r += '
'+trendIcon+' '+((trendDiff===null)?t('avg'):((trendDiff>0?'+':'')+vI(trendDiff)+'%'))+'
';
r += '
';
r += '
';
r += '
'+fmtBigNum(totalCycles)+' '+t('cycles')+' · '+fmtBigHours(totalHours)+' · '+vI(daysAvail)+' '+t('days')+'
';
r += '
'+fmtDay(oldestDay)+' → '+fmtDay(latestDay)+'
';
r += '
';
var tileCount = (hasHeating?1:0) + (hasDHW?1:0) + (hasCooling?1:0);
if(tileCount > 0){
r += '
';
var miniTile = function(icon, label, val, color, bg){
return '
'
+'
'+icon+'
'
+'
'+label+'
'
+'
'+val+'
'
+'
';
};
if(hasHeating) r += miniTile('🔥', t('heat_short'), fmtBigNum(heating.cycles), C.heating, CBG.heating);
if(hasDHW) r += miniTile('🚿', t('dhw'), fmtBigNum(dhw.cycles), C.dhw, CBG.dhw);
if(hasCooling) r += miniTile('🧊', t('cool_short'), fmtBigNum(cooling.cycles), C.cooling, CBG.cooling);
r += '
';
}
if(hasOutliers){
r += '
'
+ '🚨 ' + outlierDays.length + ' × ' + t('outlier_warn')
+ '
';
}
r += '
';
/* ===== BEST / WORST ===== */
if(bestDay || worstDay){
r += '
';
var dayCard = function(icon, label, day, color){
if(!day) return '
';
var dc = qColor(day.quality_avg);
var rel = relDays(day.day);
return '
'
+'
'+icon+' '+label+'
'
+'
'+shortDate(day.day)+' · '+rel+'
'
+'
'
+ '
'+(day.quality_avg===null?'—':vI(day.quality_avg)+'%')+'
'
+ '
'+vI(day.cycles)+'c · '+fmtBigMin(day.dur_min)+'
'
+'
'
+'
';
};
r += dayCard('🏆', t('best_day'), bestDay, QGOOD);
r += dayCard('⚠️', t('worst_day'), worstDay, QLOW);
r += '
';
}
/* ===== SPARKLINES (compact) ===== */
r += '
';
r += '
📈 '+t('sparklines')+''+vI(numDays)+' '+t('days')+'
';
r += spark;
r += '
';
/* ===== QUALITY PER DAY (dynamic colors) ===== */
if(hasQuality){
r += '
';
r += '
⭐ '+t('quality_chart')+''+t('avg')+' '+vI(avgQuality)+'%
';
r += qc;
r += chipRow([
{col:QGOOD, bg:'#E8F5E9', label:t('q_good')},
{col:QMID, bg:'#FFF3E0', label:t('q_mid')},
{col:QLOW, bg:'#FFEBEE', label:t('q_low')},
{col:C.gem, bg:'#F3E5F5', label:'┄ '+t('avg')}
], vI(qualityVals.length)+' '+t('days'));
r += '
';
}
/* ===== CYCLES CHART ===== */
r += '
';
r += '
🔄 '+t('cycles_chart')+''+t('avg')+' '+v1(avgCyclesPerDay)+t('per_day_short')+'
';
r += c1;
var cyclesChips = [];
if(hasHeating) cyclesChips.push({col:C.heating, bg:CBG.heating, label:t('legend_heat')});
if(hasDHW) cyclesChips.push({col:C.dhw, bg:CBG.dhw, label:t('legend_dhw')});
if(hasCooling) cyclesChips.push({col:C.cooling, bg:CBG.cooling, label:t('legend_cool')});
cyclesChips.push({col:C.gem, bg:CBG.gem, label:'┄ '+t('legend_gem_line')});
r += chipRow(cyclesChips, fmtBigNum(totalCycles)+' '+t('total'));
r += '
';
/* ===== DURATION CHART ===== */
r += '
';
r += '
⏱️ '+t('duration_chart')+''+t('cap')+' '+v1(c2Cap)+'h
';
r += c2;
var durChips = [];
if(hasHeating) durChips.push({col:C.heating, bg:CBG.heating, label:t('legend_heat')});
if(hasDHW) durChips.push({col:C.dhw, bg:CBG.dhw, label:t('legend_dhw')});
if(hasOutliers) durChips.push({col:QLOW, bg:'#FFEBEE', label:'⚠ '+t('clipped')});
r += chipRow(durChips, fmtBigHours(totalHours)+' '+t('total'));
r += '
';
/* ===== EVENTS ===== */
if(hasBuh || hasDefrost){
r += '
';
r += '
⚡❄️ '+t('events_chart')+''+fmtBigNum(totalBuh)+' '+t('legend_buh')+' · '+fmtBigNum(totalDefrost)+' '+t('legend_defrost')+'
';
r += strip;
var evChips = [];
if(hasBuh) evChips.push({col:C.buh, bg:CBG.buh, label:'⚡ '+t('legend_buh')+' '+vI(buhRate)+'%'});
if(hasDefrost) evChips.push({col:C.defrost, bg:CBG.defrost, label:'❄️ '+t('legend_defrost')+' '+vI(defrostRate)+'%'});
r += chipRow(evChips, t('threshold_legend')+': 15% · 35%');
r += '
';
}
r += '
';
return r;
} catch(e) {
var errMsg = (e && e.message) ? e.message : String(e);
return '⚠️ Summary error: ' + errMsg + '
';
}
}).call(this));
]]]