Skip to content

Instantly share code, notes, and snippets.

@grischard
Last active October 2, 2024 21:56
Show Gist options
  • Save grischard/ce5b9707652b67e81bc6957911f2324a to your computer and use it in GitHub Desktop.
Save grischard/ce5b9707652b67e81bc6957911f2324a to your computer and use it in GitHub Desktop.
Swatch beats Home Assistant
class SwatchBeatBase extends HTMLElement {
interval = null;
connectedCallback() {
if (!this.interval) {
this.interval = setInterval(() => this.updateBeats(), 86);
}
}
disconnectedCallback() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
updateBeats() {
// 3600 seconds in an hour; 86400 seconds in a day
const now = new Date();
const beats = (
(((now.getUTCHours() * 3600 +
now.getUTCMinutes() * 60 +
now.getUTCSeconds()) * 1000 +
now.getUTCMilliseconds() +
3600000) % 86400000) / 86400
).toFixed(3);
this.render(beats);
}
render(beats) {
throw new Error('Method "render(beats)" must be implemented');
}
setConfig(config) {
this.config = config;
}
}
class SwatchBeatCard extends SwatchBeatBase {
constructor() {
super();
const card = document.createElement("ha-card");
card.header = "Swatch Internet Beats";
this.content = document.createElement("div");
this.content.className = "card-content";
card.appendChild(this.content);
this.appendChild(card);
}
render(beats) {
this.content.textContent = `@${beats}`;
}
getCardSize() {
return 1;
}
}
class SwatchBeatBadge extends SwatchBeatBase {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<ha-badge>
<ha-icon slot="icon" icon="mdi:at"></ha-icon>
<span id="beats"></span>
</ha-badge>
`;
}
render(beats) {
const beatsElement = this.shadowRoot.getElementById('beats');
if (beatsElement) {
beatsElement.textContent = `${beats}`; // Using template literals here as well
}
}
}
customElements.define('swatch-beat-card', SwatchBeatCard);
customElements.define('swatch-beat-badge', SwatchBeatBadge);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment