Skip to content

Instantly share code, notes, and snippets.

@sam2332
Last active August 6, 2024 17:16
Show Gist options
  • Save sam2332/330f4b74ca49cf6df43d1df10ec3f3bc to your computer and use it in GitHub Desktop.
Save sam2332/330f4b74ca49cf6df43d1df10ec3f3bc to your computer and use it in GitHub Desktop.
Simple Daily Log
type: custom:simple-log-card
entity: input_text.horrible_weather_factor_trending_delta
title: Horrible History
max_entries: 10
class SimpleLogCard extends HTMLElement {
set hass(hass) {
this._hass = hass;
if (!this.content) {
const title = this.config.title || 'Sensor Log';
this.innerHTML = `
<ha-card header="${title}">
<div class="card-content"></div>
</ha-card>
`;
this.content = this.querySelector('div.card-content');
this.updateContent();
}
}
async updateContent() {
const entityId = this.config.entity;
const maxEntries = this.config.max_entries || 10; // Default to 10 entries if not specified
const history = await this.fetchHistory(entityId, maxEntries);
if (history.length > 0 && history[0].length > 0) {
const entries = history[0].slice(0, maxEntries); // Limit the number of entries
const groupedByDate = this.groupByDate(entries);
let contentHTML = '';
Object.keys(groupedByDate).sort().reverse().forEach(date => {
contentHTML += `<h4>${date}</h4><ul>`;
groupedByDate[date].reverse().forEach(state => {
const timeString = this.formatTime(state.last_changed);
contentHTML += `<li>${timeString}: ${state.state}</li>`;
});
contentHTML += '</ul>';
});
this.content.innerHTML = contentHTML;
} else {
this.content.innerHTML = '<p>No history found.</p>';
}
}
formatTime(utcDatetime) {
// Convert UTC to local time
const localDate = new Date(utcDatetime);
let hours = localDate.getHours();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
const minutes = localDate.getMinutes();
return `${hours}:${minutes < 10 ? '0' + minutes : minutes} ${ampm}`;
}
groupByDate(states) {
return states.reduce((acc, state) => {
const date = state.last_changed.split('T')[0];
if (!acc[date]) {
acc[date] = [];
}
acc[date].push(state);
return acc;
}, {});
}
async fetchHistory(entityId, maxEntries) {
const url = `history/period?filter_entity_id=${entityId}`;
const response = await this._hass.callApi('GET', url);
return response;
}
setConfig(config) {
if (!config.entity) {
throw new Error('You need to define an entity');
}
this.config = config;
}
getCardSize() {
return 3;
}
}
customElements.define('simple-log-card', SimpleLogCard);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment