Files
homelab-configs/static/index.html
T

592 lines
20 KiB
HTML

<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HA Voice Control</title>
<style>
:root {
--bg: #0d1117;
--surface: #161b22;
--border: #30363d;
--text: #e6edf3;
--text-dim: #8b949e;
--accent: #58a6ff;
--danger: #f85149;
--success: #3fb950;
--warning: #d29922;
--mic-bg: #1a2332;
--mic-active: #da3633;
--radius: 12px;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 20px;
}
header h1 {
font-size: 1.6rem;
font-weight: 600;
letter-spacing: -0.02em;
}
header p {
color: var(--text-dim);
font-size: 0.9rem;
margin-top: 4px;
}
.status-bar {
display: flex;
gap: 8px;
align-items: center;
margin-bottom: 24px;
font-size: 0.85rem;
color: var(--text-dim);
}
.status-dot {
width: 8px; height: 8px;
border-radius: 50%;
background: var(--text-dim);
}
.status-dot.connected { background: var(--success); }
.status-dot.error { background: var(--danger); }
/* ── mic button ─────────────────────────────── */
.mic-container {
position: relative;
margin-bottom: 32px;
}
.mic-ripple {
position: absolute;
inset: -8px;
border-radius: 50%;
border: 3px solid var(--mic-active);
opacity: 0;
pointer-events: none;
}
.mic-ripple.active {
animation: ripple 1.5s ease-out infinite;
}
@keyframes ripple {
0% { transform: scale(1); opacity: 0.6; }
100% { transform: scale(1.4); opacity: 0; }
}
#mic-btn {
width: 120px; height: 120px;
border-radius: 50%;
border: 3px solid var(--border);
background: var(--mic-bg);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
position: relative;
z-index: 1;
-webkit-tap-highlight-color: transparent;
user-select: none;
}
#mic-btn:hover {
border-color: var(--accent);
transform: scale(1.05);
}
#mic-btn:active {
transform: scale(0.97);
}
#mic-btn.recording {
border-color: var(--mic-active);
background: #1f1217;
box-shadow: 0 0 32px rgba(248, 81, 73, 0.25);
}
#mic-btn svg {
width: 48px; height: 48px;
fill: var(--text);
transition: fill 0.2s;
}
#mic-btn.recording svg {
fill: var(--mic-active);
}
.mic-label {
text-align: center;
margin-top: 12px;
font-size: 0.9rem;
color: var(--text-dim);
transition: color 0.2s;
}
.mic-label.recording {
color: var(--mic-active);
font-weight: 500;
}
/* ── transcriptie resultaten ────────────────── */
.result-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 16px 20px;
margin-bottom: 16px;
width: 100%;
max-width: 480px;
min-height: 48px;
display: flex;
align-items: center;
gap: 10px;
}
.result-card .icon {
font-size: 1.4rem;
flex-shrink: 0;
}
.result-card .content {
flex: 1;
font-size: 0.95rem;
line-height: 1.5;
}
.result-card .text-transcript {
font-weight: 500;
margin-bottom: 4px;
}
.result-card .text-response {
color: var(--text-dim);
font-size: 0.85rem;
}
.result-card.error { border-color: var(--danger); }
.result-card.success { border-color: var(--success); }
/* ── lichten paneel ──────────────────────────── */
.lights-panel {
width: 100%;
max-width: 480px;
}
.lights-panel h2 {
font-size: 1rem;
font-weight: 600;
margin-bottom: 12px;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.light-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
margin-bottom: 8px;
cursor: pointer;
transition: background 0.15s;
}
.light-item:hover {
background: #1c2129;
}
.light-icon {
font-size: 1.4rem;
}
.light-info {
flex: 1;
}
.light-name {
font-size: 0.95rem;
font-weight: 500;
}
.light-state {
font-size: 0.8rem;
color: var(--text-dim);
}
.light-toggle {
width: 48px; height: 28px;
border-radius: 14px;
background: var(--border);
cursor: pointer;
position: relative;
transition: background 0.2s;
border: none;
flex-shrink: 0;
}
.light-toggle.on {
background: var(--accent);
}
.light-toggle::after {
content: '';
position: absolute;
top: 3px; left: 3px;
width: 22px; height: 22px;
border-radius: 50%;
background: white;
transition: transform 0.2s;
}
.light-toggle.on::after {
transform: translateX(20px);
}
/* ── spinner ─────────────────────────────────── */
.spinner {
width: 20px; height: 20px;
border: 2px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ── responsive ──────────────────────────────── */
@media (max-width: 500px) {
#mic-btn { width: 100px; height: 100px; }
#mic-btn svg { width: 38px; height: 38px; }
}
</style>
</head>
<body>
<header>
<h1>🏠 Home Assistant Voice Control</h1>
<p>Druk op de microfoon, spreek je commando, en laat los</p>
</header>
<div class="status-bar">
<div class="status-dot" id="status-dot"></div>
<span id="status-text">Verbinden...</span>
</div>
<!-- microfoon knop -->
<div class="mic-container">
<div class="mic-ripple" id="mic-ripple"></div>
<button id="mic-btn" aria-label="Microfoon">
<svg viewBox="0 0 24 24"><path d="M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.93V21h2v-3.07A7 7 0 0 0 19 11h-2z"/></svg>
</button>
</div>
<div class="mic-label" id="mic-label">Houd ingedrukt om te spreken</div>
<!-- resultaten -->
<div id="results"></div>
<!-- laad spinner -->
<div id="loading" style="display:none; justify-content:center; margin:16px 0;">
<div class="spinner"></div>
<span style="margin-left:10px; color:var(--text-dim)">Verwerken...</span>
</div>
<!-- lichten paneel -->
<div class="lights-panel">
<h2>💡 Lampen</h2>
<div id="lights-list">
<div style="color:var(--text-dim); font-size:0.9rem;">Laden...</div>
</div>
</div>
<script>
// ── configuratie ──────────────────────────────────────
const API_BASE = window.location.origin;
// ── state ─────────────────────────────────────────────
let mediaRecorder = null;
let audioChunks = [];
let isRecording = false;
// ── DOM refs ──────────────────────────────────────────
const micBtn = document.getElementById('mic-btn');
const micLabel = document.getElementById('mic-label');
const micRipple = document.getElementById('mic-ripple');
const resultsEl = document.getElementById('results');
const lightsList = document.getElementById('lights-list');
const loadingEl = document.getElementById('loading');
const statusDot = document.getElementById('status-dot');
const statusText = document.getElementById('status-text');
// ── health check ──────────────────────────────────────
async function checkHealth() {
try {
const resp = await fetch(`${API_BASE}/api/health`);
const data = await resp.json();
statusDot.className = 'status-dot connected';
statusText.textContent = `Verbonden met HA (${data.ha_url})`;
} catch (e) {
statusDot.className = 'status-dot error';
statusText.textContent = 'Geen verbinding met server';
}
}
// ── lichten laden ─────────────────────────────────────
async function loadLights() {
try {
const resp = await fetch(`${API_BASE}/api/lights`);
const lights = await resp.json();
renderLights(lights);
} catch (e) {
lightsList.innerHTML = '<span style="color:var(--danger)">Fout bij laden lampen</span>';
}
}
function renderLights(lights) {
if (!lights || lights.length === 0) {
lightsList.innerHTML = '<span style="color:var(--text-dim)">Geen lampen gevonden</span>';
return;
}
lightsList.innerHTML = lights.map(l => {
const isOn = l.state === 'on';
const name = l.friendly_name || l.entity_id;
const brightness = l.brightness != null ? `, ${Math.round(l.brightness / 2.55)}%` : '';
return `
<div class="light-item" data-entity="${l.entity_id}">
<span class="light-icon">${isOn ? '💡' : '🌑'}</span>
<div class="light-info">
<div class="light-name">${escapeHtml(name)}</div>
<div class="light-state">${isOn ? 'Aan' + brightness : 'Uit'}</div>
</div>
<button class="light-toggle ${isOn ? 'on' : ''}" data-entity="${l.entity_id}" data-action="${isOn ? 'turn_off' : 'turn_on'}"></button>
</div>
`;
}).join('');
// event listeners voor toggle knoppen
document.querySelectorAll('.light-toggle').forEach(btn => {
btn.addEventListener('click', async (e) => {
e.stopPropagation();
const entityId = btn.dataset.entity;
const action = btn.dataset.action;
await toggleLight(entityId, action);
});
});
// klik op hele rij togglet ook
document.querySelectorAll('.light-item').forEach(item => {
item.addEventListener('click', async () => {
const btn = item.querySelector('.light-toggle');
const entityId = btn.dataset.entity;
const action = btn.dataset.action;
await toggleLight(entityId, action);
});
});
}
async function toggleLight(entityId, action) {
try {
const resp = await fetch(`${API_BASE}/api/light/control`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ entity_id: entityId, action })
});
if (resp.ok) {
addResult(action === 'turn_on' ? '💡' : '🌑', `Lamp ${action === 'turn_on' ? 'aangezet' : 'uitgezet'}`, '', 'success');
await loadLights();
}
} catch (e) {
addResult('⚠️', 'Fout bij schakelen lamp', '', 'error');
}
}
// ── resultaten tonen ──────────────────────────────────
function addResult(icon, transcript, response, type = '') {
const card = document.createElement('div');
card.className = `result-card ${type}`;
card.innerHTML = `
<span class="icon">${icon}</span>
<div class="content">
${transcript ? `<div class="text-transcript">"${escapeHtml(transcript)}"</div>` : ''}
${response ? `<div class="text-response">${escapeHtml(response)}</div>` : ''}
</div>
`;
resultsEl.prepend(card);
// max 10 resultaten bewaren
while (resultsEl.children.length > 10) {
resultsEl.lastChild.remove();
}
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// ── audio opname ──────────────────────────────────────
async function initMicrophone() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 16000,
}
});
return stream;
} catch (e) {
console.error('Microfoon toegang geweigerd:', e);
micLabel.textContent = 'Microfoon niet beschikbaar';
micLabel.style.color = 'var(--danger)';
return null;
}
}
async function startRecording() {
const stream = await initMicrophone();
if (!stream) return;
// bepaal ondersteund MIME type
const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
? 'audio/webm;codecs=opus'
: MediaRecorder.isTypeSupported('audio/webm')
? 'audio/webm'
: 'audio/wav';
try {
mediaRecorder = new MediaRecorder(stream, { mimeType });
} catch (e) {
mediaRecorder = new MediaRecorder(stream);
}
audioChunks = [];
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) audioChunks.push(e.data);
};
mediaRecorder.onstop = async () => {
// stop alle tracks
stream.getTracks().forEach(t => t.stop());
if (audioChunks.length === 0) return;
const audioBlob = new Blob(audioChunks, { type: mediaRecorder.mimeType || 'audio/webm' });
await sendAudio(audioBlob);
};
mediaRecorder.start();
isRecording = true;
updateMicUI();
}
function stopRecording() {
if (mediaRecorder && isRecording) {
mediaRecorder.stop();
isRecording = false;
updateMicUI();
}
}
function updateMicUI() {
if (isRecording) {
micBtn.classList.add('recording');
micLabel.classList.add('recording');
micLabel.textContent = 'Opnemen... laat los om te versturen';
micRipple.classList.add('active');
} else {
micBtn.classList.remove('recording');
micLabel.classList.remove('recording');
micLabel.textContent = 'Houd ingedrukt om te spreken';
micRipple.classList.remove('active');
}
}
// ── audio versturen ───────────────────────────────────
async function sendAudio(audioBlob) {
loadingEl.style.display = 'flex';
const formData = new FormData();
formData.append('audio', audioBlob, 'recording.wav');
try {
const resp = await fetch(`${API_BASE}/api/transcribe`, {
method: 'POST',
body: formData,
});
const data = await resp.json();
if (data.error) {
addResult('⚠️', data.text || '', data.error, 'error');
} else if (!data.text) {
addResult('🔇', '', data.message || 'Geen spraak gedetecteerd', '');
} else {
// HA response parsen voor weergave
const speech = extractSpeech(data.ha_result);
addResult('🎤', data.text, speech, 'success');
// herlaad lichten na actie
await loadLights();
}
} catch (e) {
addResult('❌', '', `Fout: ${e.message}`, 'error');
} finally {
loadingEl.style.display = 'none';
}
}
function extractSpeech(haResult) {
if (!haResult) return '';
try {
const speech = haResult?.response?.speech?.plain?.speech;
if (speech) return speech;
// alternatieve paden
if (haResult?.response?.speech) return JSON.stringify(haResult.response.speech);
if (haResult?.speech) return haResult.speech;
return '';
} catch (e) {
return '';
}
}
// ── event listeners ───────────────────────────────────
micBtn.addEventListener('pointerdown', (e) => {
e.preventDefault();
startRecording();
});
micBtn.addEventListener('pointerup', (e) => {
e.preventDefault();
stopRecording();
});
micBtn.addEventListener('pointerleave', (e) => {
if (isRecording) stopRecording();
});
// touch events voor mobiel
micBtn.addEventListener('touchstart', (e) => {
e.preventDefault();
startRecording();
});
micBtn.addEventListener('touchend', (e) => {
e.preventDefault();
stopRecording();
});
// keyboard support
micBtn.addEventListener('keydown', (e) => {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
startRecording();
}
});
micBtn.addEventListener('keyup', (e) => {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
stopRecording();
}
});
// ── init ──────────────────────────────────────────────
checkHealth();
loadLights();
// periodiek verversen
setInterval(loadLights, 30000);
</script>
</body>
</html>