Dashboard web FastAPI + Chart.js

- 4 vues : spectre temps reel, historique detections, background, timeline CPS
- API REST : /api/status, /api/spectrum/current, /api/spectrum/difference,
  /api/background, /api/background/spectrum, /api/history, /api/cps/timeline
- Frontend vanilla JS + Chart.js (pas de Node.js, leger pour Pi 4)
- Moniteur modifie pour exporter son etat dans /data/monitor_state.json
  et le CPS dans /data/cps_log.jsonl chaque cycle
- Nouveau conteneur Docker 'web' sur port 8080
- Theme sombre, calibration energie (E = 0.33 + 2.97 * canal)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Jacquin Antoine
2026-05-19 13:33:07 +02:00
parent 27ef0727e8
commit 1e0c1a5ea5
22 changed files with 1031 additions and 2 deletions

51
web/static/js/app.js Normal file
View File

@ -0,0 +1,51 @@
const API_BASE = '';
let refreshInterval = null;
const REFRESH_MS = 30000; // 30 seconds
// Tab navigation
document.querySelectorAll('nav a').forEach(link => {
link.addEventListener('click', e => {
e.preventDefault();
const tab = link.dataset.tab;
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
link.classList.add('active');
document.getElementById(`tab-${tab}`).classList.add('active');
// Refresh the active tab
if (tab === 'spectrum') refreshSpectrum();
if (tab === 'background') refreshBackground();
if (tab === 'cps') loadCps(24);
});
});
// Status bar refresh
async function refreshStatus() {
try {
const resp = await fetch(`${API_BASE}/api/status`);
if (!resp.ok) {
document.getElementById('status-connected').className = 'status-dot';
return;
}
const data = await resp.json();
const dot = document.getElementById('status-connected');
dot.className = data.connected && !data.stale ? 'status-dot connected' : 'status-dot';
document.getElementById('status-cps').textContent = `${data.cps.toFixed(1)} CPS`;
document.getElementById('status-live-time').textContent = `${data.cumulated_live_time_h.toFixed(1)} h`;
} catch {
document.getElementById('status-connected').className = 'status-dot';
}
}
// Auto-refresh
function startRefresh() {
refreshStatus();
refreshSpectrum();
refreshInterval = setInterval(() => {
refreshStatus();
const activeTab = document.querySelector('.tab.active')?.dataset.tab;
if (activeTab === 'spectrum') refreshSpectrum();
}, REFRESH_MS);
}
// Initialize
startRefresh();

103
web/static/js/background.js Normal file
View File

@ -0,0 +1,103 @@
let bgChart = null;
async function refreshBackground() {
try {
const [infoResp, specResp] = await Promise.all([
fetch(`${API_BASE}/api/background`),
fetch(`${API_BASE}/api/background/spectrum`)
]);
if (!infoResp.ok || !specResp.ok) {
document.getElementById('bg-stats').innerHTML = '<p style="color:#888">Background non disponible</p>';
return;
}
const info = await infoResp.json();
const spec = await specResp.json();
// Stats
document.getElementById('bg-stats').innerHTML = `
<div class="bg-stat"><div class="bg-stat-value">${info.elapsed_hours.toFixed(1)}h</div><div class="bg-stat-label">Durée</div></div>
<div class="bg-stat"><div class="bg-stat-value">${info.live_time_s.toFixed(0)}s</div><div class="bg-stat-label">Live time</div></div>
<div class="bg-stat"><div class="bg-stat-value">${info.total_counts.toFixed(0)}</div><div class="bg-stat-label">Coups</div></div>
<div class="bg-stat"><div class="bg-stat-value">${info.cps.toFixed(2)}</div><div class="bg-stat-label">CPS</div></div>
`;
// Chart
updateBackgroundChart(spec);
// Peaks table
updatePeaksTable(info.top_peaks || []);
} catch {}
}
function updateBackgroundChart(spec) {
const ctx = document.getElementById('background-chart').getContext('2d');
const chartData = {
labels: spec.energy_kev,
datasets: [{
label: 'Background',
data: spec.counts,
borderColor: '#ff9800',
backgroundColor: 'rgba(255, 152, 0, 0.1)',
borderWidth: 1,
pointRadius: 0,
fill: true,
}]
};
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { labels: { color: '#e0e0e0' } },
tooltip: {
callbacks: {
title: (items) => `${spec.energy_kev[items[0].dataIndex]} keV`,
label: (item) => `${item.raw.toFixed(1)} counts`
}
}
},
scales: {
x: {
type: 'linear',
title: { display: true, text: 'Énergie (keV)', color: '#888' },
ticks: { color: '#888', maxTicksLimit: 20 },
grid: { color: '#333' },
},
y: {
title: { display: true, text: 'Comptages', color: '#888' },
ticks: { color: '#888' },
grid: { color: '#333' },
}
}
};
if (bgChart) {
bgChart.data = chartData;
bgChart.options = options;
bgChart.update();
} else {
bgChart = new Chart(ctx, { type: 'line', data: chartData, options });
}
}
function updatePeaksTable(peaks) {
const container = document.getElementById('peaks-table');
if (!peaks || peaks.length === 0) {
container.innerHTML = '<p style="color:#888;text-align:center;padding:8px;">Pas assez de données pour identifier les pics</p>';
return;
}
let html = '<h3 style="margin-bottom:8px;color:#ff9800;">Pics détectés</h3>';
peaks.forEach(p => {
html += `<div class="peak-row">
<span style="color:#4fc3f7">${p.energy_kev.toFixed(1)} keV</span>
<span>${p.counts.toFixed(0)} cts</span>
</div>`;
});
container.innerHTML = html;
}
document.querySelector('[data-tab="background"]').addEventListener('click', refreshBackground);

83
web/static/js/cps.js Normal file
View File

@ -0,0 +1,83 @@
let cpsChart = null;
async function loadCps(hours = 24) {
// Highlight active button
document.querySelectorAll('.controls button').forEach(b => b.style.opacity = '0.6');
const activeBtn = [...document.querySelectorAll('.controls button')].find(
b => b.textContent.includes(hours <= 24 ? `${hours}h` : `${hours/24}j`) || (hours === 168 && b.textContent === '7j')
);
if (activeBtn) activeBtn.style.opacity = '1';
try {
const resp = await fetch(`${API_BASE}/api/cps/timeline?hours=${hours}`);
if (!resp.ok) return;
const data = await resp.json();
if (!data.data_points || data.data_points.length === 0) {
return;
}
const labels = data.data_points.map(d => d.ts);
const cpsValues = data.data_points.map(d => d.cps);
updateCpsChart(labels, cpsValues);
} catch {}
}
function updateCpsChart(labels, values) {
const ctx = document.getElementById('cps-chart').getContext('2d');
const chartData = {
labels: labels,
datasets: [{
label: 'CPS',
data: values,
borderColor: '#4caf50',
backgroundColor: 'rgba(76, 175, 80, 0.1)',
borderWidth: 1.5,
pointRadius: 0,
fill: true,
tension: 0.3,
}]
};
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { labels: { color: '#e0e0e0' } },
},
scales: {
x: {
type: 'time',
time: {
tooltipFormat: 'dd/MM HH:mm',
displayFormats: { minute: 'HH:mm', hour: 'HH:mm', day: 'dd/MM' }
},
title: { display: true, text: 'Temps', color: '#888' },
ticks: { color: '#888', maxTicksLimit: 12 },
grid: { color: '#333' },
},
y: {
title: { display: true, text: 'CPS', color: '#888' },
ticks: { color: '#888' },
grid: { color: '#333' },
beginAtZero: true,
}
}
};
if (cpsChart) {
cpsChart.data = chartData;
cpsChart.options = options;
cpsChart.update();
} else {
// Chart.js needs the date adapter for time axis
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js';
script.onload = () => {
cpsChart = new Chart(ctx, { type: 'line', data: chartData, options });
};
document.head.appendChild(script);
}
}

39
web/static/js/history.js Normal file
View File

@ -0,0 +1,39 @@
async function loadHistory() {
try {
const resp = await fetch(`${API_BASE}/api/history`);
if (!resp.ok) return;
const reports = await resp.json();
const container = document.getElementById('history-list');
if (reports.length === 0) {
container.innerHTML = '<p style="color:#888;text-align:center;padding:20px;">Aucun rapport disponible</p>';
return;
}
let html = '';
reports.forEach(r => {
const isoText = r.isotopes.length > 0 ? r.isotopes.join(', ') : 'background uniquement';
html += `<div class="history-item" onclick="toggleDetails(this)">
<div class="history-header">
<span class="history-date">${r.date.split('T')[0]}</span>
<span class="history-cps">${r.cps_mean.toFixed(1)} CPS</span>
<span class="history-isotopes">${r.isotope_count} isotope(s)</span>
</div>
<div class="history-details">
<p>Live time: ${r.live_time_hours.toFixed(1)}h | Total: ${r.total_counts} coups</p>
<p>Isotopes: ${isoText}</p>
<p>Background: ${r.background_subtracted ? 'soustrait' : 'non soustrait'}</p>
</div>
</div>`;
});
container.innerHTML = html;
} catch {}
}
function toggleDetails(el) {
const details = el.querySelector('.history-details');
details.classList.toggle('open');
}
// Load on tab switch
document.querySelector('[data-tab="history"]').addEventListener('click', loadHistory);

97
web/static/js/spectrum.js Normal file
View File

@ -0,0 +1,97 @@
let spectrumChart = null;
let currentSpectrumData = null;
async function refreshSpectrum() {
const showDiff = document.getElementById('show-difference').checked;
const endpoint = showDiff ? '/api/spectrum/difference' : '/api/spectrum/current';
try {
const resp = await fetch(`${API_BASE}${endpoint}`);
if (!resp.ok) return;
const data = await resp.json();
currentSpectrumData = data;
updateSpectrumChart(data);
updateIsotopesTable(data.isotopes_detected || []);
} catch {}
}
function updateSpectrumChart(data) {
const logScale = document.getElementById('log-scale').checked;
const ctx = document.getElementById('spectrum-chart').getContext('2d');
const chartData = {
labels: data.energy_kev,
datasets: [{
label: data.background_subtracted ? 'Spectre (background soustrait)' : 'Spectre cumulé',
data: data.counts,
borderColor: '#4fc3f7',
backgroundColor: 'rgba(79, 195, 247, 0.1)',
borderWidth: 1,
pointRadius: 0,
fill: true,
}]
};
const options = {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 300 },
plugins: {
legend: { labels: { color: '#e0e0e0' } },
tooltip: {
callbacks: {
title: (items) => {
const idx = items[0].dataIndex;
return `${data.energy_kev[idx]} keV`;
},
label: (item) => `${item.raw.toFixed(1)} counts`
}
}
},
scales: {
x: {
type: 'linear',
title: { display: true, text: 'Énergie (keV)', color: '#888' },
ticks: { color: '#888', maxTicksLimit: 20 },
grid: { color: '#333' },
},
y: {
type: logScale ? 'logarithmic' : 'linear',
title: { display: true, text: 'Comptages', color: '#888' },
ticks: { color: '#888' },
grid: { color: '#333' },
}
}
};
if (spectrumChart) {
spectrumChart.data = chartData;
spectrumChart.options = options;
spectrumChart.update();
} else {
spectrumChart = new Chart(ctx, { type: 'line', data: chartData, options });
}
}
function updateIsotopesTable(isotopes) {
const container = document.getElementById('isotopes-table');
if (!isotopes || isotopes.length === 0) {
container.innerHTML = '<p style="color:#888;text-align:center;padding:8px;">Aucun isotope détecté (background uniquement)</p>';
return;
}
let html = '<h3 style="margin-bottom:8px;color:#4fc3f7;">Isotopes détectés</h3>';
isotopes.forEach(iso => {
const probColor = iso.probability > 0.9 ? '#4caf50' : iso.probability > 0.7 ? '#ff9800' : '#f44336';
html += `<div class="isotope-row">
<span class="isotope-name">${iso.isotope}</span>
<span class="isotope-prob" style="color:${probColor}">${(iso.probability * 100).toFixed(1)}%</span>
<span class="isotope-activity">${iso.activity_bq.toFixed(1)} Bq</span>
</div>`;
});
container.innerHTML = html;
}
// Event listeners
document.getElementById('show-difference').addEventListener('change', refreshSpectrum);
document.getElementById('log-scale').addEventListener('change', refreshSpectrum);