Files
home-automation/apps/ui/templates/dashboard.html
2025-11-10 16:58:46 +01:00

1052 lines
36 KiB
HTML

<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Automation</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 2rem;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
header {
background: white;
border-radius: 16px;
padding: 2rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
margin-bottom: 2rem;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 1rem;
flex-wrap: wrap;
}
.header-content {
flex: 1;
min-width: 200px;
}
h1 {
color: #333;
margin-bottom: 0.5rem;
}
.header-buttons {
display: flex;
gap: 0.5rem;
align-items: center;
}
.refresh-btn,
.collapse-all-btn {
padding: 0.75rem;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
min-height: 44px;
min-width: 44px;
display: flex;
align-items: center;
justify-content: center;
}
.refresh-btn:hover,
.collapse-all-btn:hover {
background: #5568d3;
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
.refresh-btn:active,
.collapse-all-btn:active {
transform: translateY(0);
}
.refresh-icon {
font-size: 1.5rem;
line-height: 1;
transition: transform 0.3s;
}
.refresh-icon.spinning {
animation: spin 0.6s linear;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.collapse-all-icon {
font-size: 1.25rem;
transition: transform 0.3s;
line-height: 1;
}
.collapse-all-icon.collapsed {
transform: rotate(-90deg);
}
.status {
display: inline-block;
padding: 0.25rem 0.75rem;
border-radius: 12px;
font-size: 0.875rem;
font-weight: 500;
}
.status.connected {
background: #d4edda;
color: #155724;
}
.status.disconnected {
background: #f8d7da;
color: #721c24;
}
.room {
background: white;
border-radius: 20px;
margin-bottom: 1rem;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
overflow: hidden;
transition: box-shadow 0.2s;
}
.room:hover {
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}
.room-header {
padding: 1.5rem 2rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
background: white;
transition: background-color 0.2s;
user-select: none;
}
.room-header:hover {
background: #f8f9fa;
}
.room-header:active {
background: #e9ecef;
}
.room-title {
color: #333;
font-size: 1.5rem;
font-weight: 700;
display: flex;
align-items: center;
gap: 0.75rem;
margin: 0;
}
.room-toggle {
font-size: 1.5rem;
color: #667eea;
transition: transform 0.3s;
line-height: 1;
}
.room-toggle.collapsed {
transform: rotate(-90deg);
}
.room-content {
padding: 0 2rem 2rem 2rem;
max-height: 5000px;
overflow: hidden;
transition: max-height 0.3s ease-out, padding 0.3s ease-out;
}
.room-content.collapsed {
max-height: 0;
padding-top: 0;
padding-bottom: 0;
}
.devices {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.5rem;
}
.device-card {
background: white;
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.device-header {
margin-bottom: 1.5rem;
}
.device-name {
font-size: 1.5rem;
font-weight: 600;
color: #333;
margin-bottom: 0.25rem;
}
.device-type {
font-size: 0.875rem;
color: #666;
text-transform: uppercase;
}
.device-id {
font-size: 0.75rem;
color: #999;
margin-top: 0.25rem;
font-family: 'Courier New', monospace;
}
.device-state {
padding: 0.5rem 1rem;
background: #f8f9fa;
border-radius: 8px;
margin: 1rem 0;
font-family: 'Courier New', monospace;
font-size: 0.875rem;
}
.state-label {
color: #666;
font-weight: 500;
}
.state-value {
color: #333;
font-weight: 600;
}
.state-value.on {
color: #28a745;
}
.state-value.off {
color: #dc3545;
}
.controls {
display: flex;
flex-direction: column;
gap: 1rem;
}
.toggle-button {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
color: white;
}
.toggle-button.on {
background: #28a745;
}
.toggle-button.on:hover {
background: #218838;
}
.toggle-button.off {
background: #6c757d;
}
.toggle-button.off:hover {
background: #5a6268;
}
.brightness-control {
margin-top: 1rem;
}
.brightness-label {
font-size: 0.875rem;
color: #666;
display: block;
margin-bottom: 0.5rem;
}
.brightness-slider {
width: 100%;
height: 8px;
border-radius: 4px;
background: #ddd;
outline: none;
-webkit-appearance: none;
}
.brightness-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
}
.brightness-slider::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
border: none;
}
/* Thermostat styles */
.thermostat-display {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
margin: 1rem 0;
}
.temp-reading {
background: #f8f9fa;
border-radius: 8px;
padding: 1rem;
text-align: center;
}
.temp-label {
font-size: 0.75rem;
color: #666;
text-transform: uppercase;
margin-bottom: 0.25rem;
}
.temp-value {
font-size: 2rem;
font-weight: 700;
color: #333;
}
.temp-unit {
font-size: 1rem;
color: #999;
}
.temp-controls {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
}
.temp-button {
flex: 1;
padding: 0.75rem;
border: none;
border-radius: 8px;
font-size: 1.125rem;
font-weight: 700;
cursor: pointer;
transition: all 0.2s;
background: #667eea;
color: white;
min-height: 44px;
}
.temp-button:hover {
background: #5568d3;
}
.temp-button:active {
transform: scale(0.95);
}
.events {
margin-top: 2rem;
background: white;
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.events h2 {
color: #333;
margin-bottom: 1rem;
font-size: 1.25rem;
}
.event-list {
max-height: 300px;
overflow-y: auto;
}
.event-item {
padding: 0.75rem;
border-left: 3px solid #667eea;
background: #f8f9fa;
margin-bottom: 0.5rem;
border-radius: 4px;
font-size: 0.875rem;
}
.event-time {
color: #666;
font-size: 0.75rem;
}
.event-data {
color: #333;
margin-top: 0.25rem;
font-family: 'Courier New', monospace;
}
.empty-state {
background: white;
border-radius: 16px;
padding: 3rem;
text-align: center;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.empty-state p {
color: #666;
margin-bottom: 0.5rem;
}
.hint {
font-size: 0.875rem;
color: #999;
}
</style>
</head>
<body>
<div class="container">
<header>
<div class="header-content">
<h1>🏠 Home Automation</h1>
<p>Realtime Status: <span class="status disconnected" id="connection-status">Verbinde...</span></p>
</div>
<div class="header-buttons">
<button class="refresh-btn" onclick="refreshPage()" title="Seite aktualisieren">
<span class="refresh-icon" id="refresh-icon"></span>
</button>
<button class="collapse-all-btn" onclick="toggleAllRooms()" title="Alle Räume ein-/ausklappen">
<span class="collapse-all-icon" id="collapse-all-icon"></span>
</button>
</div>
</header>
{% if rooms %}
{% for room in rooms %}
<section class="room">
<div class="room-header" onclick="toggleRoom('room-{{ loop.index }}')">
<h2 class="room-title">{{ room.name }}</h2>
<span class="room-toggle" id="toggle-room-{{ loop.index }}"></span>
</div>
<div class="room-content" id="room-{{ loop.index }}">
<div class="devices">
{% for device in room.devices %}
<div class="device-card" data-device-id="{{ device.device_id }}">
<div class="device-header">
<div class="device-name">{{ device.icon }} {{ device.title }}</div>
<div class="device-type">
{% if device.type == "light" %}
Light
{% if device.features.brightness %}• Dimmbar{% endif %}
{% elif device.type == "thermostat" %}
Thermostat
{% else %}
{{ device.type or "Unknown" }}
{% endif %}
</div>
<div class="device-id">{{ device.device_id }}</div>
</div>
{% if device.type == "light" %}
<div class="device-state">
<span class="state-label">Status:</span>
<span class="state-value off" id="state-{{ device.device_id }}">off</span>
{% if device.features.brightness %}
<br>
<span class="state-label">Helligkeit:</span>
<span class="state-value" id="brightness-{{ device.device_id }}">50</span>%
{% endif %}
</div>
{% if device.features.power %}
<div class="controls">
<button
class="toggle-button off"
id="toggle-{{ device.device_id }}"
onclick="toggleDevice('{{ device.device_id }}')">
Einschalten
</button>
{% if device.features.brightness %}
<div class="brightness-control">
<label for="brightness-slider-{{ device.device_id }}" class="brightness-label">
Helligkeit: <span id="brightness-value-{{ device.device_id }}">50</span>%
</label>
<input
type="range"
class="brightness-slider"
id="brightness-slider-{{ device.device_id }}"
min="0"
max="100"
value="50"
oninput="updateBrightnessValue('{{ device.device_id }}', this.value)"
onchange="setBrightness('{{ device.device_id }}', this.value)">
</div>
{% endif %}
</div>
{% endif %}
{% elif device.type == "thermostat" %}
<div class="thermostat-display">
<div class="temp-reading">
<div class="temp-label">Ist</div>
<div class="temp-value">
<span id="state-{{ device.device_id }}-current">--</span>
<span class="temp-unit">°C</span>
</div>
</div>
<div class="temp-reading">
<div class="temp-label">Soll</div>
<div class="temp-value">
<span id="state-{{ device.device_id }}-target">21.0</span>
<span class="temp-unit">°C</span>
</div>
</div>
</div>
<div class="temp-controls">
<button class="temp-button" onclick="adjustTarget('{{ device.device_id }}', -1.0)">
-1.0
</button>
<button class="temp-button" onclick="adjustTarget('{{ device.device_id }}', 1.0)">
+1.0
</button>
</div>
{% endif %}
</div>
{% endfor %}
</div>
</div>
</section>
{% endfor %}
{% else %}
<div class="empty-state">
<p>Keine Räume oder Geräte konfiguriert.</p>
<p class="hint">Prüfe config/layout.yaml und das API-Gateway.</p>
</div>
{% endif %}
<div class="events">
<h2>📡 Realtime Events</h2>
<div class="event-list" id="event-list">
<p style="color: #666; font-size: 0.875rem;">Warte auf Events...</p>
</div>
</div>
</div>
<script>
// Toggle room visibility
function toggleRoom(roomId) {
const content = document.getElementById(roomId);
const toggle = document.getElementById(`toggle-${roomId}`);
if (content && toggle) {
content.classList.toggle('collapsed');
toggle.classList.toggle('collapsed');
}
}
// Refresh page with animation
function refreshPage() {
const icon = document.getElementById('refresh-icon');
icon.classList.add('spinning');
// Reload page after brief animation
setTimeout(() => {
window.location.reload();
}, 300);
}
// Toggle all rooms
function toggleAllRooms() {
const allContents = document.querySelectorAll('.room-content');
const allToggles = document.querySelectorAll('.room-toggle');
const buttonIcon = document.getElementById('collapse-all-icon');
// Check if any room is expanded
const anyExpanded = Array.from(allContents).some(content => !content.classList.contains('collapsed'));
if (anyExpanded) {
// Collapse all
allContents.forEach(content => content.classList.add('collapsed'));
allToggles.forEach(toggle => toggle.classList.add('collapsed'));
buttonIcon.classList.add('collapsed');
} else {
// Expand all
allContents.forEach(content => content.classList.remove('collapsed'));
allToggles.forEach(toggle => toggle.classList.remove('collapsed'));
buttonIcon.classList.remove('collapsed');
}
}
// Set room icons based on room name
document.addEventListener('DOMContentLoaded', () => {
const roomTitles = document.querySelectorAll('.room-title');
roomTitles.forEach(title => {
const roomName = title.textContent.trim().toLowerCase();
let icon = '🏠'; // Default
if (roomName.includes('wohn') || roomName.includes('living')) icon = '🛋️';
else if (roomName.includes('schlaf') || roomName.includes('bed')) icon = '🛏️';
else if (roomName.includes('küch') || roomName.includes('kitchen')) icon = '🍳';
else if (roomName.includes('bad') || roomName.includes('bath')) icon = '🛁';
else if (roomName.includes('büro') || roomName.includes('office')) icon = '💼';
else if (roomName.includes('kind') || roomName.includes('child')) icon = '🧸';
else if (roomName.includes('garten') || roomName.includes('garden')) icon = '🌿';
else if (roomName.includes('garage')) icon = '🚗';
else if (roomName.includes('keller') || roomName.includes('basement')) icon = '📦';
else if (roomName.includes('dach') || roomName.includes('attic')) icon = '🏚️';
// Replace the ::before pseudo-element with actual emoji
const originalText = title.textContent.trim();
title.innerHTML = `${icon} ${originalText}`;
});
});
// Clean up SSE connection before page unload
window.addEventListener('beforeunload', () => {
if (eventSource) {
console.log('Closing SSE connection before unload');
eventSource.close();
eventSource = null;
}
});
// API_BASE injected from backend (supports Docker/K8s environments)
window.API_BASE = '{{ api_base }}';
window.RUNTIME_CONFIG = window.RUNTIME_CONFIG || {};
// Helper function to construct API URLs
function api(url) {
return `${window.API_BASE}${url}`;
}
// iOS/Safari Polyfill laden (nur wenn nötig)
(function() {
var isIOS = /iP(hone|od|ad)/.test(navigator.platform) ||
(navigator.userAgent.includes("Mac") && "ontouchend" in document);
if (isIOS && typeof window.EventSourcePolyfill === "undefined") {
var s = document.createElement("script");
s.src = "https://cdn.jsdelivr.net/npm/event-source-polyfill@1.0.31/src/eventsource.min.js";
s.onerror = function() {
console.warn("EventSource polyfill konnte nicht geladen werden");
};
document.head.appendChild(s);
}
})();
let eventSource = null;
let currentState = {};
let thermostatTargets = {};
// Initialize device states
{% for room in rooms %}
{% for device in room.devices %}
{% if device.type == "light" %}
currentState['{{ device.device_id }}'] = 'off';
{% elif device.type == "thermostat" %}
thermostatTargets['{{ device.device_id }}'] = 21.0;
{% endif %}
{% endfor %}
{% endfor %}
// Toggle device state
async function toggleDevice(deviceId) {
const newState = currentState[deviceId] === 'on' ? 'off' : 'on';
try {
const response = await fetch(api(`/devices/${deviceId}/set`), {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: 'light',
payload: {
power: newState
}
})
});
if (response.ok) {
console.log(`Sent ${newState} command to ${deviceId}`);
addEvent({
action: 'command_sent',
device_id: deviceId,
state: newState
});
}
} catch (error) {
console.error('Failed to toggle device:', error);
}
}
// Update brightness value display
function updateBrightnessValue(deviceId, value) {
const valueSpan = document.getElementById(`brightness-value-${deviceId}`);
if (valueSpan) {
valueSpan.textContent = value;
}
}
// Set brightness
async function setBrightness(deviceId, brightness) {
try {
const response = await fetch(api(`/devices/${deviceId}/set`), {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: 'light',
payload: {
brightness: parseInt(brightness)
}
})
});
if (response.ok) {
console.log(`Sent brightness ${brightness} to ${deviceId}`);
addEvent({
action: 'brightness_set',
device_id: deviceId,
brightness: parseInt(brightness)
});
}
} catch (error) {
console.error('Failed to set brightness:', error);
}
}
// Adjust thermostat target temperature
async function adjustTarget(deviceId, delta) {
const currentTarget = thermostatTargets[deviceId] || 21.0;
const newTarget = Math.max(5.0, Math.min(30.0, currentTarget + delta));
try {
const response = await fetch(api(`/devices/${deviceId}/set`), {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: 'thermostat',
payload: {
target: newTarget
}
})
});
if (response.ok) {
console.log(`Sent target ${newTarget} to ${deviceId}`);
addEvent({
action: 'target_adjusted',
device_id: deviceId,
target: newTarget
});
}
} catch (error) {
console.error('Failed to adjust target:', error);
}
}
// Update device UI
function updateDeviceUI(deviceId, power, brightness) {
currentState[deviceId] = power;
const stateSpan = document.getElementById(`state-${deviceId}`);
const toggleButton = document.getElementById(`toggle-${deviceId}`);
if (stateSpan) {
stateSpan.textContent = power;
stateSpan.className = `state-value ${power}`;
}
if (toggleButton) {
if (power === 'on') {
toggleButton.textContent = 'Ausschalten';
toggleButton.className = 'toggle-button on';
} else {
toggleButton.textContent = 'Einschalten';
toggleButton.className = 'toggle-button off';
}
// Force reflow for iOS Safari
void toggleButton.offsetHeight;
}
// Update brightness display and slider
if (brightness !== undefined) {
const brightnessSpan = document.getElementById(`brightness-${deviceId}`);
const brightnessValue = document.getElementById(`brightness-value-${deviceId}`);
const brightnessSlider = document.getElementById(`brightness-slider-${deviceId}`);
if (brightnessSpan) {
brightnessSpan.textContent = brightness;
}
if (brightnessValue) {
brightnessValue.textContent = brightness;
}
if (brightnessSlider) {
brightnessSlider.value = brightness;
}
}
}
// Update thermostat UI
function updateThermostatUI(deviceId, current, target, mode) {
const currentSpan = document.getElementById(`state-${deviceId}-current`);
const targetSpan = document.getElementById(`state-${deviceId}-target`);
if (current !== undefined && currentSpan) {
currentSpan.textContent = current.toFixed(1);
}
if (target !== undefined) {
if (targetSpan) {
targetSpan.textContent = target.toFixed(1);
}
thermostatTargets[deviceId] = target;
}
}
// Add event to list
function addEvent(event) {
const eventList = document.getElementById('event-list');
// Clear placeholder
if (eventList.children.length === 1 && eventList.children[0].tagName === 'P') {
eventList.innerHTML = '';
}
const eventItem = document.createElement('div');
eventItem.className = 'event-item';
const now = new Date().toLocaleTimeString('de-DE');
eventItem.innerHTML = `
<div class="event-time">${now}</div>
<div class="event-data">${JSON.stringify(event, null, 2)}</div>
`;
eventList.insertBefore(eventItem, eventList.firstChild);
// Keep only last 10 events
while (eventList.children.length > 10) {
eventList.removeChild(eventList.lastChild);
}
}
// Safari/iOS-kompatibler SSE Client mit Auto-Reconnect
let reconnectDelay = 2500;
let reconnectTimer = null;
// Global handleSSE function für SSE-Nachrichten
window.handleSSE = function(data) {
console.log('SSE message:', data);
addEvent(data);
// Update device state
if (data.type === 'state' && data.device_id && data.payload) {
const card = document.querySelector(`[data-device-id="${data.device_id}"]`);
if (!card) {
console.warn(`No card found for device ${data.device_id}`);
return;
}
// Check if it's a light
if (data.payload.power !== undefined) {
currentState[data.device_id] = data.payload.power;
updateDeviceUI(
data.device_id,
data.payload.power,
data.payload.brightness
);
}
// Check if it's a thermostat
if (data.payload.target !== undefined || data.payload.current !== undefined) {
if (data.payload.target !== undefined) {
thermostatTargets[data.device_id] = data.payload.target;
}
updateThermostatUI(
data.device_id,
data.payload.current,
data.payload.target
);
}
}
};
function cleanupSSE() {
if (eventSource) {
try {
eventSource.close();
} catch(e) {
console.error('Error closing EventSource:', e);
}
eventSource = null;
}
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
}
function scheduleReconnect() {
if (reconnectTimer) return;
console.log(`Reconnecting in ${reconnectDelay}ms...`);
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connectSSE();
// Backoff bis 10s
reconnectDelay = Math.min(reconnectDelay * 2, 10000);
}, reconnectDelay);
}
function connectSSE() {
cleanupSSE();
const REALTIME_URL = (window.RUNTIME_CONFIG && window.RUNTIME_CONFIG.REALTIME_URL)
? window.RUNTIME_CONFIG.REALTIME_URL
: api('/realtime');
console.log('Connecting to SSE:', REALTIME_URL);
try {
// Verwende Polyfill wenn verfügbar, sonst native EventSource
const EventSourceImpl = window.EventSourcePolyfill || window.EventSource;
eventSource = new EventSourceImpl(REALTIME_URL, {
withCredentials: false
});
eventSource.onopen = function() {
console.log('SSE connected successfully');
reconnectDelay = 2500; // Reset backoff
document.getElementById('connection-status').textContent = 'Verbunden';
document.getElementById('connection-status').className = 'status connected';
};
eventSource.onmessage = function(evt) {
if (!evt || !evt.data) return;
// Heartbeats beginnen mit ":" -> ignorieren
if (typeof evt.data === "string" && evt.data.charAt(0) === ":") {
return;
}
try {
const data = JSON.parse(evt.data);
if (window.handleSSE) {
window.handleSSE(data);
}
} catch (e) {
console.error('Error parsing SSE message:', e);
}
};
eventSource.onerror = function(error) {
console.error('SSE error:', error, 'readyState:', eventSource?.readyState);
document.getElementById('connection-status').textContent = 'Getrennt';
document.getElementById('connection-status').className = 'status disconnected';
// Safari/iOS verliert Netz beim App-Switch: ruhig reconnecten
scheduleReconnect();
};
} catch (error) {
console.error('Failed to create EventSource:', error);
document.getElementById('connection-status').textContent = 'Getrennt';
document.getElementById('connection-status').className = 'status disconnected';
scheduleReconnect();
}
}
// Visibility-Change Handler für iOS App-Switch
document.addEventListener('visibilitychange', function() {
if (!document.hidden) {
// Wenn wieder sichtbar & keine offene Verbindung: verbinden
if (!eventSource || eventSource.readyState !== 1) {
console.log('Page visible again, reconnecting SSE...');
connectSSE();
}
}
});
// Start SSE connection
connectSSE();
// Load initial device states
async function loadDevices() {
try {
const response = await fetch(api('/devices/states'));
const states = await response.json();
console.log('Loaded initial device states:', states);
// Update UI with initial states
for (const [deviceId, state] of Object.entries(states)) {
if (state.power !== undefined) {
// It's a light
currentState[deviceId] = state.power;
updateDeviceUI(deviceId, state.power, state.brightness);
} else if (state.target !== undefined) {
// It's a thermostat
if (state.target) thermostatTargets[deviceId] = state.target;
updateThermostatUI(deviceId, state.current, state.target);
}
}
} catch (error) {
console.error('Failed to load initial device states:', error);
}
}
// Load initial states before connecting SSE
loadDevices().then(() => {
console.log('Initial states loaded, now connecting SSE...');
});
</script>
</body>
</html>