BioVibe / index.html
Hezu06's picture
Remove duplicate tab-ble div to clean up HTML structure
6aa457e
Raw
History Blame Contribute Delete
44.2 kB
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bio-Vibe Web</title>
<link rel="icon" href="data:,">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #1a1a2e;
color: #e94560;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
padding: 20px;
box-sizing: border-box;
}
.container {
background-color: #16213e;
padding: 40px;
border-radius: 15px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
max-width: 620px;
width: 100%;
}
h1 { color: #fff; margin-bottom: 5px; }
.subtitle { color: #a2a2bd; margin-bottom: 20px; }
#bpm-display {
font-size: 80px;
font-weight: bold;
margin: 15px 0;
text-shadow: 0 0 15px #e94560;
transition: color 0.3s ease;
}
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.05); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
/* ---- TABS ---- */
.tab-group {
display: flex;
justify-content: center;
gap: 0;
margin-bottom: 20px;
border-radius: 8px;
overflow: hidden;
border: 1px solid #0f3460;
}
.tab-btn {
flex: 1;
background: #0f3460;
color: #a2a2bd;
border: none;
padding: 10px 16px;
font-size: 14px;
cursor: pointer;
transition: 0.2s;
font-weight: bold;
}
.tab-btn.active { background: #4ecca3; color: #1a1a2e; }
.tab-btn:hover:not(.active) { background: #1a3a6e; color: #fff; }
.tab-panel { display: none; }
.tab-panel.active { display: block; }
/* ---- MANUAL INPUT ---- */
.manual-group {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
margin: 10px 0 16px;
}
#manual-bpm-input {
background: #0f3460;
border: 1px solid #4ecca3;
border-radius: 8px;
color: #fff;
font-size: 28px;
font-weight: bold;
width: 110px;
text-align: center;
padding: 8px;
}
#manual-bpm-input:focus { outline: 2px solid #4ecca3; }
#btn-manual-set {
background: #4ecca3;
color: #1a1a2e;
border: none;
padding: 10px 18px;
font-size: 15px;
border-radius: 8px;
cursor: pointer;
font-weight: bold;
transition: 0.2s;
}
#btn-manual-set:hover { background: #38b499; }
/* ---- BUTTONS ---- */
.button-group {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 12px;
margin-top: 10px;
}
button {
background-color: #0f3460;
color: white;
border: none;
padding: 13px 22px;
font-size: 15px;
border-radius: 8px;
cursor: pointer;
transition: 0.3s;
font-weight: bold;
}
button:hover { background-color: #4ecca3; color: #1a1a2e; }
button:disabled { background-color: #2a2a3e; cursor: not-allowed; color: #555; }
#btn-stop { background-color: #8b0000; }
#btn-stop:hover { background-color: #ff4d4d; color: white; }
#btn-stop:disabled { background-color: #2a2a3e; }
/* ---- STATUS ---- */
#status {
margin-top: 18px;
font-size: 13px;
font-style: italic;
min-height: 20px;
}
.status-ok { color: #4ecca3; }
.status-err { color: #ff4d4d; }
.status-info { color: #a2a2bd; }
/* ---- DEBUG LOG ---- */
.debug-section {
margin-top: 20px;
text-align: left;
}
.debug-toggle {
background: none;
border: none;
color: #555;
font-size: 12px;
cursor: pointer;
padding: 4px 0;
font-style: italic;
}
.debug-toggle:hover { color: #a2a2bd; background: none; }
#debug-log {
display: none;
background: #0a0a1a;
border-radius: 6px;
padding: 10px;
font-size: 11px;
color: #4ecca3;
font-family: monospace;
max-height: 160px;
overflow-y: auto;
margin-top: 6px;
text-align: left;
}
/* ---- QUICK BPM ZONES ---- */
.zone-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:8px; margin:12px 0; }
.zone-btn { background:#0f3460; border:1px solid #1a3a6e; border-radius:10px; color:#fff;
padding:10px 4px; font-size:13px; cursor:pointer; transition:0.2s;
display:flex; flex-direction:column; align-items:center; gap:3px; }
.zone-btn:hover { background:#1a4070; border-color:#4ecca3; }
.zone-btn.active-zone { border-color:#4ecca3; background:#0a2844; }
.zone-btn .zone-emoji { font-size:20px; }
.zone-btn .zone-label { font-size:10px; color:#a2a2bd; }
.zone-btn .zone-bpm { font-size:12px; color:#4ecca3; font-weight:bold; }
.auto-row { display:flex; align-items:center; justify-content:center; gap:10px;
margin-top:8px; font-size:13px; color:#a2a2bd; }
.toggle-wrap { position:relative; width:36px; height:20px; }
.toggle-wrap input { opacity:0; width:100%; height:100%; position:absolute; cursor:pointer; margin:0; z-index:2; }
.toggle-track { position:absolute; inset:0; background:#1a3a6e; border-radius:10px; transition:background 0.2s; }
.toggle-wrap input:checked ~ .toggle-track { background:#4ecca3; }
.toggle-thumb { position:absolute; top:3px; left:3px; width:14px; height:14px;
background:#fff; border-radius:50%; transition:transform 0.2s; pointer-events:none; }
.toggle-wrap input:checked ~ .toggle-thumb { transform:translateX(16px); }
#refresh-interval-wrap { display:none; align-items:center; gap:6px; }
#refresh-interval-wrap.visible { display:flex; }
#refresh-sec { width:52px; background:#0f3460; border:1px solid #4ecca3;
border-radius:6px; color:#fff; font-size:14px; text-align:center; padding:3px; }
/* ---- NOTICE ---- */
.notice {
background: #0f2040;
border-left: 3px solid #e94560;
border-radius: 0 6px 6px 0;
padding: 10px 14px;
margin-bottom: 14px;
font-size: 13px;
color: #a2a2bd;
text-align: left;
}
.notice strong { color: #e94560; }
/* ---- BLE DEVICE CARD ---- */
#ble-idle { }
#ble-card { display:none; }
.scan-hint {
font-size: 12px; color: #4a5a7a; margin-top: 8px; font-style: italic;
}
/* Scanning animation */
.scan-ring-wrap {
display: flex; align-items: center; justify-content: center;
gap: 14px; margin: 12px 0 8px;
}
.scan-ring {
width: 44px; height: 44px; border-radius: 50%;
border: 3px solid transparent;
border-top-color: #4ecca3;
border-right-color: #4ecca366;
animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.scan-label { color: #4ecca3; font-size: 14px; font-weight: bold; }
/* Connected device card */
.device-card {
background: linear-gradient(135deg, #0a2040 0%, #0f3060 100%);
border: 1px solid #4ecca355;
border-radius: 14px;
padding: 16px 18px;
margin: 10px 0;
display: flex;
align-items: center;
gap: 14px;
text-align: left;
position: relative;
overflow: hidden;
}
.device-card::before {
content: '';
position: absolute;
inset: 0;
background: radial-gradient(ellipse at 20% 50%, #4ecca318 0%, transparent 60%);
pointer-events: none;
}
.device-icon-wrap {
width: 52px; height: 52px; border-radius: 50%;
background: linear-gradient(135deg, #0f3460, #1a4a80);
border: 2px solid #4ecca355;
display: flex; align-items: center; justify-content: center;
font-size: 26px; flex-shrink: 0;
}
.device-info { flex: 1; min-width: 0; }
.device-name {
color: #fff; font-size: 15px; font-weight: bold;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.device-sub {
color: #a2a2bd; font-size: 12px; margin-top: 2px;
}
.device-badges {
display: flex; gap: 6px; margin-top: 6px; flex-wrap: wrap;
}
.badge {
background: #0f3460; border: 1px solid #1a4a80;
border-radius: 20px; padding: 2px 9px;
font-size: 11px; color: #a2a2bd;
}
.badge.connected {
background: #0a3020; border-color: #4ecca355; color: #4ecca3;
}
.badge.subscribing {
background: #2a1a00; border-color: #e9a02055; color: #e9a020;
}
.badge.no-hr {
background: #300a0a; border-color: #e9456055; color: #e94560;
}
/* Signal bars */
.signal-wrap {
display: flex; align-items: flex-end; gap: 2px; height: 18px;
}
.sig-bar {
width: 4px; border-radius: 2px; background: #4ecca3;
opacity: 0.25; transition: opacity 0.4s;
}
.sig-bar.active { opacity: 1; }
.sig-bar:nth-child(1) { height: 5px; }
.sig-bar:nth-child(2) { height: 9px; }
.sig-bar:nth-child(3) { height: 13px; }
.sig-bar:nth-child(4) { height: 18px; }
/* Disconnect button */
#btn-disconnect {
background: transparent;
border: 1px solid #e9456066;
color: #e94560;
padding: 6px 13px;
font-size: 12px;
border-radius: 8px;
cursor: pointer;
font-weight: bold;
transition: 0.2s;
flex-shrink: 0;
}
#btn-disconnect:hover {
background: #e9456020; border-color: #e94560;
}
/* Reconnect button (shown when disconnected) */
#btn-reconnect {
display: none;
background: #4ecca322;
border: 1px solid #4ecca355;
color: #4ecca3;
padding: 6px 13px;
font-size: 12px;
border-radius: 8px;
cursor: pointer;
font-weight: bold;
transition: 0.2s;
flex-shrink: 0;
}
#btn-reconnect:hover { background: #4ecca344; }
/* Pulse dot (connection alive indicator) */
.pulse-dot {
width: 8px; height: 8px; border-radius: 50%;
background: #4ecca3;
box-shadow: 0 0 0 0 #4ecca3aa;
animation: pulseDot 1.8s ease infinite;
flex-shrink: 0;
}
@keyframes pulseDot {
0% { box-shadow: 0 0 0 0 #4ecca3aa; }
70% { box-shadow: 0 0 0 7px #4ecca300; }
100% { box-shadow: 0 0 0 0 #4ecca300; }
}
.pulse-dot.dead {
background: #e94560; box-shadow: none; animation: none;
}
</style>
</head>
<body>
<div class="container">
<h1>Bio-Vibe 🎧</h1>
<p class="subtitle">Âm nhạc trị liệu AI theo Nhịp tim</p>
<div id="bpm-display">-- BPM</div>
<!-- TABS -->
<div class="tab-group">
<button class="tab-btn active" onclick="switchTab('ble')">📡 Kết nối BLE</button>
<button class="tab-btn" onclick="switchTab('manual')">✏️ Nhập thủ công</button>
</div>
<!-- TAB: BLE -->
<div id="tab-ble" class="tab-panel active">
<!-- STATE: idle / scanning -->
<div id="ble-idle">
<div class="button-group">
<button id="btn-connect">📡 Quét thiết bị BLE</button>
</div>
<p class="scan-hint">Trình duyệt sẽ mở hộp thoại chọn thiết bị Bluetooth</p>
</div>
<!-- STATE: scanning spinner (shown briefly) -->
<div id="ble-scanning" style="display:none; padding:8px 0 4px;">
<div class="scan-ring-wrap">
<div class="scan-ring"></div>
<span class="scan-label">Đang kết nối…</span>
</div>
</div>
<!-- STATE: connected device card -->
<div id="ble-card" style="display:none;">
<div class="device-card">
<div class="device-icon-wrap" id="dev-icon"></div>
<div class="device-info">
<div class="device-name" id="dev-name">Unknown Device</div>
<div class="device-sub" id="dev-sub">Đang kiểm tra characteristics…</div>
<div class="device-badges">
<span class="badge connected" id="badge-conn">● Đã kết nối</span>
<span class="badge" id="badge-hr" style="display:none"></span>
<span class="badge" id="badge-svc"></span>
</div>
</div>
<div style="display:flex; flex-direction:column; align-items:center; gap:8px;">
<div class="signal-wrap" id="signal-bars">
<div class="sig-bar active"></div>
<div class="sig-bar active"></div>
<div class="sig-bar active"></div>
<div class="sig-bar"></div>
</div>
<div class="pulse-dot" id="pulse-dot"></div>
</div>
<div style="display:flex; flex-direction:column; gap:6px; align-items:flex-end;">
<button id="btn-disconnect">Ngắt kết nối</button>
<button id="btn-reconnect">🔄 Kết nối lại</button>
</div>
</div>
</div>
</div>
<!-- TAB: MANUAL -->
<div id="tab-manual" class="tab-panel">
<p style="color:#a2a2bd; font-size:13px; margin-bottom:6px;">
Nhìn BPM trên Samsung Health → chọn vùng hoặc nhập chính xác bên dưới.
</p>
<!-- Quick zone buttons -->
<div class="zone-grid">
<button class="zone-btn" onclick="setZone(55,'Nghỉ ngơi')">
<span class="zone-emoji">😴</span>
<span class="zone-label">Nghỉ ngơi</span>
<span class="zone-bpm">~55 BPM</span>
</button>
<button class="zone-btn" onclick="setZone(70,'Nhẹ nhàng')">
<span class="zone-emoji">🚶</span>
<span class="zone-label">Nhẹ nhàng</span>
<span class="zone-bpm">~70 BPM</span>
</button>
<button class="zone-btn" onclick="setZone(95,'Vận động')">
<span class="zone-emoji">🏃</span>
<span class="zone-label">Vận động</span>
<span class="zone-bpm">~95 BPM</span>
</button>
<button class="zone-btn" onclick="setZone(130,'Cường độ cao')">
<span class="zone-emoji">🔥</span>
<span class="zone-label">Cường độ cao</span>
<span class="zone-bpm">~130 BPM</span>
</button>
</div>
<!-- Precise input -->
<div class="manual-group">
<input type="number" id="manual-bpm-input" min="30" max="220" value="75"
onkeydown="if(event.key==='Enter') setManualBpm()" />
<button id="btn-manual-set" onclick="setManualBpm()">Áp dụng</button>
</div>
<!-- Auto refresh reminder -->
<div class="auto-row">
<label class="toggle-wrap">
<input type="checkbox" id="auto-refresh-toggle" onchange="toggleAutoRefresh(this.checked)">
<span class="toggle-track"></span>
<span class="toggle-thumb"></span>
</label>
<span>Nhắc cập nhật BPM mỗi</span>
<span id="refresh-interval-wrap">
<input type="number" id="refresh-sec" min="10" max="300" value="30"> giây
</span>
</div>
</div>
<!-- PLAYBACK CONTROLS -->
<div class="button-group" style="margin-top:18px;">
<button id="btn-generate">2. Sinh nhạc AI</button>
<button id="btn-stop" disabled>3. Dừng nhạc</button>
</div>
<div id="status" class="status-info">Chưa có BPM...</div>
<!-- DEBUG -->
<div class="debug-section">
<button class="debug-toggle" onclick="toggleDebug()">▶ Xem log BLE debug</button>
<div id="debug-log"></div>
</div>
</div>
<script>
// ===============================
// STATE
// ===============================
let currentBpm = 0;
let bpmHistory = [];
let currentAudio = null;
let debugVisible = false;
let ws = null; // Biến giữ kết nối WebSocket
const bpmDisplay = document.getElementById('bpm-display');
const statusEl = document.getElementById('status');
const btnConnect = document.getElementById('btn-connect');
const btnGenerate = document.getElementById('btn-generate');
const btnStop = document.getElementById('btn-stop');
const debugLog = document.getElementById('debug-log');
// ===============================
// UI HELPERS
// ===============================
function setStatus(msg, type = 'info') {
statusEl.textContent = msg;
statusEl.className = 'status-' + type;
}
function log(msg) {
const line = document.createElement('div');
line.textContent = '[' + new Date().toLocaleTimeString() + '] ' + msg;
debugLog.appendChild(line);
debugLog.scrollTop = debugLog.scrollHeight;
console.log(msg);
}
function toggleDebug() {
debugVisible = !debugVisible;
debugLog.style.display = debugVisible ? 'block' : 'none';
}
function switchTab(name) {
document.querySelectorAll('.tab-btn').forEach((b, i) => {
b.classList.toggle('active', (i === 0 && name === 'ble') || (i === 1 && name === 'manual'));
});
document.getElementById('tab-ble').classList.toggle('active', name === 'ble');
document.getElementById('tab-manual').classList.toggle('active', name === 'manual');
}
// ===============================
// BPM SMOOTHING
// ===============================
function smoothBpm(val) {
bpmHistory.push(val);
if (bpmHistory.length > 5) bpmHistory.shift();
return Math.round(bpmHistory.reduce((a, b) => a + b, 0) / bpmHistory.length);
}
function applyBpm(raw, source) {
if (raw < 30 || raw > 220) return false;
if (currentBpm !== 0 && Math.abs(raw - currentBpm) > 40) return false;
const smoothed = smoothBpm(raw);
currentBpm = smoothed;
bpmDisplay.textContent = currentBpm + ' BPM';
bpmDisplay.style.color = '#e94560';
setStatus('BPM nhận từ: ' + source, 'ok');
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ bpm: currentBpm }));
}
return true;
}
// ===============================
// MANUAL BPM
// ===============================
function setManualBpm() {
const val = parseInt(document.getElementById('manual-bpm-input').value, 10);
if (isNaN(val) || val < 30 || val > 220) {
setStatus('Giá trị BPM không hợp lệ (30–220)', 'err');
return;
}
bpmHistory = [];
applyBpm(val, 'Nhập thủ công');
}
function setZone(bpm, label) {
document.getElementById('manual-bpm-input').value = bpm;
bpmHistory = [];
applyBpm(bpm, label);
// Highlight active zone
document.querySelectorAll('.zone-btn').forEach(b => b.classList.remove('active-zone'));
event.currentTarget.classList.add('active-zone');
}
let autoRefreshTimer = null;
function toggleAutoRefresh(on) {
const wrap = document.getElementById('refresh-interval-wrap');
wrap.classList.toggle('visible', on);
if (autoRefreshTimer) { clearInterval(autoRefreshTimer); autoRefreshTimer = null; }
if (on) {
const sec = parseInt(document.getElementById('refresh-sec').value, 10) || 30;
autoRefreshTimer = setInterval(() => {
setStatus(`⏰ Hãy kiểm tra BPM trên Samsung Health và cập nhật!`, 'info');
// Flash BPM display
bpmDisplay.style.opacity = '0.4';
setTimeout(() => bpmDisplay.style.opacity = '1', 600);
}, sec * 1000);
setStatus(`Sẽ nhắc cập nhật BPM mỗi ${sec} giây`, 'ok');
}
}
// ===============================
// PARSE CHUẨN BLE Heart Rate (0x2A37)
// ===============================
function parseHeartRateMeasurement(dataView) {
/*
* Byte 0: Flags
* bit 0 = 0 → Heart Rate Value là UINT8 (byte 1)
* bit 0 = 1 → Heart Rate Value là UINT16 (bytes 1-2, little-endian)
*/
const flags = dataView.getUint8(0);
const is16bit = (flags & 0x01) !== 0;
return is16bit
? dataView.getUint16(1, true)
: dataView.getUint8(1);
}
// ===============================
// HANDLE INCOMING CHARACTERISTIC DATA
// ===============================
function handleCharData(event, uuid, serviceUuid) {
const dv = event.target.value;
const raw = [];
for (let i = 0; i < dv.byteLength; i++) raw.push(dv.getUint8(i));
log(`UUID ${uuid.substring(0,8)}… DATA: [${raw.join(', ')}]`);
const HR_MEASUREMENT_UUID = '00002a37-0000-1000-8000-00805f9b34fb';
// 1. Nếu đúng UUID chuẩn Heart Rate Measurement → parse theo spec
if (uuid === HR_MEASUREMENT_UUID) {
if (dv.byteLength >= 2) {
const bpm = parseHeartRateMeasurement(dv);
log(`Standard HR parse → ${bpm} BPM`);
applyBpm(bpm, 'HR chuẩn BLE');
}
return;
}
// 2. Fallback heuristic cho proprietary chars
// Duyệt từng byte, lấy byte đầu tiên nằm trong [40, 180]
for (let i = 0; i < raw.length; i++) {
const v = raw[i];
if (v >= 40 && v <= 180) {
log(`Heuristic byte[${i}] = ${v} BPM`);
applyBpm(v, `Heuristic (${uuid.substring(0,8)}…)`);
break;
}
}
}
// ===============================
// BLE STATE
// ===============================
let bleDevice = null;
let bleServer = null;
let bleSubCount = 0;
const bleIdle = document.getElementById('ble-idle');
const bleScanning = document.getElementById('ble-scanning');
const bleCard = document.getElementById('ble-card');
const devIcon = document.getElementById('dev-icon');
const devName = document.getElementById('dev-name');
const devSub = document.getElementById('dev-sub');
const badgeConn = document.getElementById('badge-conn');
const badgeHr = document.getElementById('badge-hr');
const badgeSvc = document.getElementById('badge-svc');
const pulseDot = document.getElementById('pulse-dot');
const btnDisconnect = document.getElementById('btn-disconnect');
const btnReconnect = document.getElementById('btn-reconnect');
function guessDeviceIcon(name) {
if (!name) return '📡';
const n = name.toLowerCase();
if (n.includes('polar') || n.includes('hrm') || n.includes('chest')) return '💓';
if (n.includes('garmin')) return '🏃';
if (n.includes('galaxy') || n.includes('watch') || n.includes('samsung')) return '⌚';
if (n.includes('mi band') || n.includes('xiaomi') || n.includes('amazfit')) return '📿';
if (n.includes('fitbit')) return '💪';
return '⌚';
}
function showBleCard(name, subText) {
bleIdle.style.display = 'none';
bleScanning.style.display = 'none';
bleCard.style.display = 'block';
devIcon.textContent = guessDeviceIcon(name);
devName.textContent = name || 'Unknown Device';
devSub.textContent = subText || '';
}
function setBleConnected() {
badgeConn.textContent = '● Đã kết nối';
badgeConn.className = 'badge connected';
pulseDot.classList.remove('dead');
btnDisconnect.style.display = 'inline-block';
btnReconnect.style.display = 'none';
}
function setBleDisconnected() {
badgeConn.textContent = '○ Mất kết nối';
badgeConn.className = 'badge no-hr';
pulseDot.classList.add('dead');
btnDisconnect.style.display = 'none';
btnReconnect.style.display = 'inline-block';
// Animate signal bars off
document.querySelectorAll('.sig-bar').forEach(b => b.classList.remove('active'));
}
function resetBleUI() {
bleCard.style.display = 'none';
bleScanning.style.display = 'none';
bleIdle.style.display = 'block';
badgeHr.style.display = 'none';
bleDevice = null; bleServer = null; bleSubCount = 0;
}
// ===============================
// BLE CONNECT — auto scan tất cả services
// ===============================
async function doBleConnect() {
if (!navigator.bluetooth) {
setStatus('Trình duyệt không hỗ trợ Web Bluetooth!', 'err');
return;
}
try {
setStatus('Đang mở hộp thoại BLE…', 'info');
log('Bắt đầu scan BLE...');
// Show scanning state while picker is open
bleIdle.style.display = 'none';
bleScanning.style.display = 'block';
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: [
'heart_rate', 'battery_service', 'device_information', 'generic_access',
'0000fee0-0000-1000-8000-00805f9b34fb',
'0000fee1-0000-1000-8000-00805f9b34fb',
'0000181d-0000-1000-8000-00805f9b34fb',
'0000fd00-0000-1000-8000-00805f9b34fb',
'0000180d-0000-1000-8000-00805f9b34fb',
]
});
bleDevice = device;
log(`Device: ${device.name || '(no name)'} id=${device.id}`);
showBleCard(device.name, 'Đang kết nối GATT…');
setStatus('Đang kết nối GATT…', 'info');
// Listen for unexpected disconnects
device.addEventListener('gattserverdisconnected', onGattDisconnected);
bleServer = await device.gatt.connect();
const services = await bleServer.getPrimaryServices();
log(`Tìm thấy ${services.length} service(s)`);
badgeSvc.textContent = `${services.length} services`;
let subscribed = 0;
for (const svc of services) {
log(`Service: ${svc.uuid}`);
let chars;
try { chars = await svc.getCharacteristics(); }
catch (e) { log(` Không đọc được chars: ${e.message}`); continue; }
for (const char of chars) {
const props = char.properties;
log(` Char: ${char.uuid} [notify=${props.notify} indicate=${props.indicate} read=${props.read}]`);
if (props.notify || props.indicate) {
try {
await char.startNotifications();
char.addEventListener('characteristicvaluechanged',
(ev) => handleCharData(ev, char.uuid, svc.uuid));
log(` ✅ Subscribed: ${char.uuid}`);
subscribed++;
} catch (e) { log(` ❌ Subscribe failed: ${e.message}`); }
}
}
}
bleSubCount = subscribed;
setBleConnected();
if (subscribed === 0) {
badgeHr.textContent = '✗ Không có HR';
badgeHr.className = 'badge no-hr';
badgeHr.style.display = 'inline-block';
devSub.textContent = 'Không đọc được HR — thử tab Nhập thủ công';
setStatus('Kết nối OK nhưng thiết bị không stream HR. Thử tab Nhập thủ công.', 'err');
} else {
badgeHr.textContent = `♥ ${subscribed} HR char`;
badgeHr.className = 'badge subscribing';
badgeHr.style.display = 'inline-block';
devSub.textContent = `Đã subscribe ${subscribed} characteristic — đang chờ BPM…`;
setStatus(`Đã subscribe ${subscribed} characteristic, đang chờ BPM…`, 'ok');
}
} catch (err) {
log(`Lỗi: ${err.message}`);
setStatus('Lỗi BLE: ' + err.message, 'err');
resetBleUI();
}
}
// ===============================
// GATT DISCONNECTED EVENT
// ===============================
function onGattDisconnected() {
log('⚠ GATT server disconnected (đồng hồ tự ngắt hoặc ra khỏi tầm)');
setStatus('⚠ Mất kết nối BLE — nhấn "Kết nối lại" để thử lại.', 'err');
setBleDisconnected();
devSub.textContent = 'Mất kết nối — ra khỏi tầm Bluetooth?';
}
// ===============================
// DISCONNECT
// ===============================
function doDisconnect() {
if (bleDevice && bleDevice.gatt.connected) {
bleDevice.gatt.disconnect();
log('Đã ngắt kết nối BLE theo yêu cầu');
}
setBleDisconnected();
devSub.textContent = 'Đã ngắt kết nối';
setStatus('Đã ngắt kết nối BLE.', 'info');
}
// ===============================
// RECONNECT
// ===============================
async function doReconnect() {
if (!bleDevice) { resetBleUI(); return; }
try {
devSub.textContent = 'Đang kết nối lại…';
btnReconnect.disabled = true;
setStatus('Đang kết nối lại GATT…', 'info');
bleServer = await bleDevice.gatt.connect();
const services = await bleServer.getPrimaryServices();
let subscribed = 0;
for (const svc of services) {
let chars;
try { chars = await svc.getCharacteristics(); } catch { continue; }
for (const char of chars) {
const props = char.properties;
if (props.notify || props.indicate) {
try {
await char.startNotifications();
char.addEventListener('characteristicvaluechanged',
(ev) => handleCharData(ev, char.uuid, svc.uuid));
subscribed++;
} catch {}
}
}
}
bleSubCount = subscribed;
setBleConnected();
devSub.textContent = `Kết nối lại thành công — ${subscribed} char`;
setStatus('Kết nối lại BLE thành công!', 'ok');
} catch (err) {
log(`Reconnect failed: ${err.message}`);
setStatus('Kết nối lại thất bại: ' + err.message, 'err');
devSub.textContent = 'Kết nối lại thất bại';
} finally {
btnReconnect.disabled = false;
}
}
btnConnect.addEventListener('click', doBleConnect);
btnDisconnect.addEventListener('click', doDisconnect);
btnReconnect.addEventListener('click', doReconnect);
// ================================================================
// AUDIO CHAIN — volume boosted, gain staging cẩn thận
// ================================================================
const masterGain = new Tone.Gain(1.5).toDestination(); // +3.5dB tổng thể
const limiter = new Tone.Limiter(-0.3).connect(masterGain); // limiter thoáng hơn
const compressor = new Tone.Compressor({
threshold: -14, ratio: 3, attack: 0.008, release: 0.18
}).connect(limiter);
const eq = new Tone.EQ3({ low: 1, mid: 0, high: 2 }).connect(compressor); // low cut: bỏ rumble
const stereo = new Tone.StereoWidener(0.65).connect(eq);
const reverb = new Tone.Reverb({ decay: 3.5, wet: 0.38 }).connect(stereo); // wet sẽ thay đổi theo BPM
const delay = new Tone.FeedbackDelay({ delayTime: "8n", feedback: 0.28, wet: 0.18 }).connect(reverb);
// 🎹 PIANO — volume tăng lên, kết nối thẳng vào delay
const piano = new Tone.Sampler({
volume: 4, // +4dB so với trước (trước là 0)
urls: {
A1:"A1.mp3", C2:"C2.mp3", "D#2":"Ds2.mp3", "F#2":"Fs2.mp3",
A2:"A2.mp3", C3:"C3.mp3", "D#3":"Ds3.mp3", "F#3":"Fs3.mp3",
A3:"A3.mp3", C4:"C4.mp3", "D#4":"Ds4.mp3", "F#4":"Fs4.mp3",
A4:"A4.mp3", C5:"C5.mp3"
},
baseUrl: "https://raw.githubusercontent.com/Tonejs/audio/master/salamander/",
release: 1
}).connect(delay);
// 🌊 STRING PAD — fatsawtooth + lowpass filter: ấm, organic, blend với piano
// "sine" tạo tiếng sóng não vì không có harmonics.
// "fatsawtooth" (3 voice detuned) qua filter ~700Hz = string pad lofi chuẩn.
const padFilter = new Tone.Filter({
frequency: 700,
type: "lowpass",
rolloff: -24 // cắt mạnh để không overlap với piano
}).connect(reverb);
const pad = new Tone.PolySynth(Tone.Synth, {
volume: -9,
oscillator: { type: "fatsawtooth", count: 3, spread: 25 },
envelope: { attack: 1.4, decay: 0.4, sustain: 0.75, release: 3.5 }
}).connect(padFilter);
// Bass synth đã bỏ — chord pad đủ low-end, không cần thêm sub
log("🎹 Đã khởi tạo audio chain. Volume boosted.");
setStatus("Sẵn sàng sinh nhạc AI", "ok");
// ================================================================
// BPM-REACTIVE: thay đổi texture theo nhịp tim
// ================================================================
function applyBpmTexture(bpm) {
// ── ENTRAINMENT LOGIC ──────────────────────────────────────────
// Nhịp tim cao = cơ thể đang stress → nhạc kéo ngược lại: chậm,
// mơ màng, ambient hơn để hạ nhiệt.
// Nhịp tim thấp = nghỉ ngơi → nhạc có thể nhẹ nhàng groove hơn.
// Reverb: BPM CAO = nhiều reverb hơn (mơ màng, bay bổng, dịu)
// BPM thấp = ít reverb (rõ ràng, có chiều sâu nhẹ)
const reverbWet = bpm < 70 ? 0.28 :
bpm < 90 ? 0.35 :
bpm < 110 ? 0.46 : 0.58;
reverb.wet.rampTo(reverbWet, 2.5);
// Delay feedback: BPM cao = echo dài hơn (hypnotic, calming)
const delayFb = bpm < 80 ? 0.16 : bpm < 110 ? 0.24 : 0.34;
delay.feedback.rampTo(delayFb, 2.5);
// Pad volume: BPM cao = pad nổi hơn (ambient nhấn chìm, che melody)
// BPM thấp = pad lùi, melody groove rõ hơn
const padVol = bpm < 75 ? -12 : bpm < 100 ? -8 : -4;
pad.volume.rampTo(padVol, 2.5);
// Pad attack: BPM cao = attack chậm (drifting), thấp = attack vừa
const padAttack = bpm < 75 ? 0.6 : bpm < 100 ? 1.2 : 2.2;
pad.set({ envelope: { attack: padAttack } });
// Lowpass cutoff: BPM cao (calming) → filter tối hơn (500Hz), thấp → sáng hơn (800Hz)
const filterFreq = bpm < 75 ? 800 : bpm < 100 ? 650 : 500;
padFilter.frequency.rampTo(filterFreq, 2.5);
// Nhạc tempo: BPM cao → tempo chậm hơn để kéo nhịp tim xuống
// map BPM [40,180] → music tempo [85, 55] BPM (inverse linear)
const musicTempo = Math.round(85 - (bpm - 40) * (30 / 140));
Tone.getTransport().bpm.rampTo(Math.max(52, Math.min(88, musicTempo)), 3);
// BPM display color theo mức độ stress
// (màu vẫn phản ánh nhịp tim thực, không phải tempo nhạc)
const color = bpm < 70 ? '#4ecca3' : // xanh — bình tĩnh
bpm < 90 ? '#a0d8ef' : // xanh dương — nhẹ nhàng
bpm < 110 ? '#f9c74f' : // vàng — đang tăng
'#e94560'; // đỏ — cần hạ nhiệt
bpmDisplay.style.color = color;
bpmDisplay.style.textShadow = `0 0 20px ${color}`;
log(`🎚 Texture (entrainment) → reverb:${reverbWet} delayFb:${delayFb} padVol:${padVol} musicTempo:${musicTempo}`);
}
// Override applyBpm để gọi texture update
const _origApplyBpm = applyBpm;
// Không thể override function declaration, thêm hook vào ws.send thay thế
function sendBpmToServer(bpm) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ bpm }));
}
applyBpmTexture(bpm);
}
// ================================================================
// WEBSOCKET — sinh nhạc
// ================================================================
btnGenerate.addEventListener('click', async () => {
if (currentBpm === 0) {
alert('Chưa có BPM! Kết nối đồng hồ hoặc nhập thủ công.');
return;
}
await Tone.start();
await Tone.loaded();
log("✅ Piano samples loaded");
// Khôi phục gain (có thể đang = 0 nếu vừa Stop)
masterGain.gain.cancelScheduledValues(Tone.now());
masterGain.gain.setValueAtTime(1.5, Tone.now());
if (ws) ws.close();
setStatus(`Đang kết nối AI với ${currentBpm} BPM…`, 'info');
btnGenerate.textContent = 'AI đang truyền nốt…';
btnGenerate.disabled = true;
btnStop.disabled = false;
bpmDisplay.style.animation = 'pulse 1s infinite';
// Khởi động texture ngay
applyBpmTexture(currentBpm);
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
ws = new WebSocket(`${protocol}//${window.location.host}/ws/vibe`);
ws.onopen = () => {
setStatus('🎵 Đang phát nhạc Real-time…', 'ok');
ws.send(JSON.stringify({ bpm: currentBpm }));
};
let startTime = Tone.now() + 0.15;
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// Sync Transport BPM với music_bpm server trả về (entrainment tempo)
if (data.music_bpm) {
Tone.getTransport().bpm.rampTo(data.music_bpm, 2);
}
data.notes.forEach(n => {
const noteStr = Tone.Frequency(n.note, "midi").toNote();
const t = startTime + n.time;
if (n.type === "melody") {
// Velocity melody cũng phản ánh BPM: cao → piano mạnh hơn
const velBoost = currentBpm > 100 ? 1.15 : 1.0;
const vel = Math.min(1, (n.velocity / 127) * velBoost);
piano.triggerAttackRelease(noteStr, n.duration, t, vel);
}
else if (n.type === "chord") {
pad.triggerAttackRelease(noteStr, n.duration, t, n.velocity / 127);
}
});
startTime += data.batch_duration;
};
// Mỗi khi BPM thay đổi từ đồng hồ/manual → cập nhật texture + drum
const origApply = applyBpm;
// Patch ws.send để bắt BPM change
const _origSend = ws.send.bind(ws);
ws.send = function(data) {
try {
const parsed = JSON.parse(data);
if (parsed.bpm) applyBpmTexture(parsed.bpm);
} catch {}
return _origSend(data);
};
ws.onerror = (err) => {
log('WebSocket Error: ' + err);
setStatus('Lỗi kết nối tới AI!', 'err');
};
ws.onclose = () => {
btnGenerate.textContent = '2. Sinh nhạc AI';
btnGenerate.disabled = false;
btnStop.disabled = true;
bpmDisplay.style.animation = 'none';
};
});
// ================================================================
// STOP — tắt ngay lập tức, không chờ note đã schedule trong buffer
// ================================================================
btnStop.addEventListener('click', () => {
if (ws) { ws.close(); ws = null; }
// cancelScheduledValues triệt tiêu mọi ramp đang chờ,
// setValueAtTime(0) tắt gain TỨC THỜI — kể cả note đã queue sẵn.
// Gain KHÔNG được restore ở đây — chỉ restore khi nhấn Generate lại.
masterGain.gain.cancelScheduledValues(Tone.now());
masterGain.gain.setValueAtTime(0, Tone.now());
piano.releaseAll();
pad.releaseAll();
setStatus('Đã dừng nhạc.', 'info');
});
</script>
</body>
</html>