Files
esp32s3_canlogger_mcp2515/graph_viewer.h
2026-03-12 21:14:40 +00:00

1161 lines
48 KiB
C++
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ifndef GRAPH_VIEWER_H
#define GRAPH_VIEWER_H
const char graph_viewer_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CAN Signal Graph Viewer</title>
<style>
:root {
--bg: #0e1117;
--panel: #161b24;
--card: #1c2230;
--border: #2d3748;
--accent: #43cea2;
--accent2: #38ef7d;
--blue: #58a6ff;
--red: #f85149;
--yellow: #e3b341;
--text: #e6edf3;
--muted: #8b949e;
--radius: 10px;
}
* { margin:0; padding:0; box-sizing:border-box; }
html, body { height:100%; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: var(--bg);
color: var(--text);
overflow-x: hidden;
font-size: 14px;
}
/* ── Header ── */
.header {
background: linear-gradient(135deg, #1a2744 0%, #1e1a3a 100%);
padding: 12px 16px;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
gap: 10px;
}
.header h1 {
font-size: 1.05em;
font-weight: 700;
color: var(--accent);
white-space: nowrap;
}
.header p {
font-size: 0.8em;
color: var(--muted);
margin: 0;
}
.header-spacer { flex: 1; }
/* ── Nav ── */
.nav {
background: var(--panel);
border-bottom: 1px solid var(--border);
display: flex;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
}
.nav::-webkit-scrollbar { display: none; }
.nav a {
display: inline-flex;
align-items: center;
padding: 10px 14px;
text-decoration: none;
color: var(--muted);
font-size: 0.8em;
font-weight: 500;
border-bottom: 2px solid transparent;
white-space: nowrap;
transition: color 0.2s, border-color 0.2s;
min-width: unset;
}
.nav a:hover { color: var(--text); }
.nav a.active { color: var(--accent); border-bottom-color: var(--accent); }
/* ── Controls ── */
.controls {
background: var(--panel);
border-bottom: 1px solid var(--border);
padding: 8px 12px;
display: flex;
flex-wrap: wrap;
gap: 6px;
align-items: center;
}
.control-group {
display: flex;
align-items: center;
gap: 4px;
flex-wrap: wrap;
}
.control-label {
font-size: 0.72em;
color: var(--muted);
white-space: nowrap;
padding-right: 2px;
}
.ctrl-sep {
width: 1px;
height: 20px;
background: var(--border);
margin: 0 4px;
}
.btn {
padding: 5px 11px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg);
color: var(--muted);
font-size: 0.78em;
font-weight: 600;
cursor: pointer;
transition: all 0.15s;
white-space: nowrap;
font-family: inherit;
-webkit-tap-highlight-color: transparent;
touch-action: manipulation;
}
.btn:hover { border-color: var(--accent); color: var(--accent); }
.btn:active { transform: scale(0.96); }
.btn.active {
background: rgba(67,206,162,0.15);
border-color: var(--accent);
color: var(--accent);
}
.btn-success { border-color: #3fb950; color: #3fb950; }
.btn-success.active, .btn-success:hover { background: rgba(63,185,80,0.15); }
.btn-danger { border-color: var(--red); color: var(--red); }
.btn-danger:hover { background: rgba(248,81,73,0.12); }
.btn-info { border-color: var(--blue); color: var(--blue); }
.btn-info.active, .btn-info:hover { background: rgba(88,166,255,0.15); }
.btn-warning { border-color: var(--yellow); color: var(--yellow); }
.btn-warning.active, .btn-warning:hover { background: rgba(227,179,65,0.15); }
/* ── Stats bar ── */
.stats-bar {
display: flex;
flex-wrap: wrap;
gap: 14px;
padding: 5px 14px;
background: var(--bg);
border-bottom: 1px solid var(--border);
font-size: 0.75em;
color: var(--muted);
}
.stats-bar strong { color: var(--accent); margin-left: 3px; }
/* ── Status pill ── */
.status {
padding: 4px 10px;
border-radius: 20px;
font-size: 0.72em;
font-weight: 600;
background: rgba(67,206,162,0.12);
color: var(--accent);
border: 1px solid rgba(67,206,162,0.3);
transition: all 0.3s;
white-space: nowrap;
}
.status.disconnected {
background: rgba(248,81,73,0.12);
color: var(--red);
border-color: rgba(248,81,73,0.3);
}
/* ── Graph grid ── */
.graphs {
padding: 10px;
display: grid;
/* ★ 모바일 핵심: min(100%, 440px) 로 가로 스크롤 방지 */
grid-template-columns: repeat(auto-fit, minmax(min(100%, 440px), 1fr));
gap: 10px;
}
.graph-container {
background: var(--card);
border-radius: var(--radius);
border: 1px solid var(--border);
overflow: hidden;
}
.graph-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
border-bottom: 1px solid var(--border);
background: rgba(67,206,162,0.05);
gap: 8px;
}
.graph-title {
font-size: 0.82em;
font-weight: 700;
color: var(--accent);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.graph-value {
font-size: 1em;
font-weight: 700;
color: var(--accent2);
font-family: 'Courier New', 'SF Mono', monospace;
white-space: nowrap;
flex-shrink: 0;
}
/* ★ canvas: CSS padding/background 제거, height만 설정 */
canvas {
display: block;
width: 100%;
height: 200px;
border: none;
}
/* ── Responsive ── */
@media (max-width: 480px) {
.controls { padding: 6px 8px; gap: 5px; }
.ctrl-sep { display: none; }
.btn { padding: 6px 9px; font-size: 0.8em; }
.header h1 { font-size: 0.95em; }
canvas { height: 175px; }
.stats-bar { gap: 8px; font-size: 0.7em; }
}
@media (min-width: 768px) {
canvas { height: 230px; }
}
@media (min-width: 1200px) {
canvas { height: 260px; }
}
</style>
</head>
<body>
<div class="header">
<div>
<h1>📈 CAN Signal Graph</h1>
<p>Viewing <span id="graph-count">0</span> signals</p>
</div>
<div class="header-spacer"></div>
<div class="status" id="status-pill">Connecting...</div>
</div>
<div class="nav">
<a href="/">📊 Monitor</a>
<a href="/transmit">📤 Transmit</a>
<a href="/graph">📈 Graph</a>
<a href="/graph-view" class="active">📊 Graph View</a>
<a href="/settings"> Settings</a>
<a href="/serial">📟 Serial1</a>
<a href="/serial2">📟 Serial2</a>
</div>
<div class="controls">
<div class="control-group">
<button class="btn btn-success active" id="btn-start" onclick="startGraphing()">▶ Start</button>
<button class="btn btn-danger" id="btn-stop" onclick="stopGraphing()">■ Stop</button>
</div>
<div class="ctrl-sep"></div>
<div class="control-group">
<span class="control-label">Scale:</span>
<button class="btn btn-info active" id="btn-index-mode" onclick="setScaleMode('index')">Index</button>
<button class="btn btn-info" id="btn-time-mode" onclick="setScaleMode('time')">Time</button>
</div>
<div class="ctrl-sep"></div>
<div class="control-group">
<span class="control-label">Range:</span>
<button class="btn btn-warning active" id="btn-range-10s" onclick="setRangeMode('10s')">10s</button>
<button class="btn btn-warning" id="btn-range-30s" onclick="setRangeMode('30s')">30s</button>
<button class="btn btn-warning" id="btn-range-all" onclick="setRangeMode('all')">All</button>
</div>
<div class="ctrl-sep"></div>
<div class="control-group">
<span class="control-label">Plot:</span>
<button class="btn btn-info active" id="btn-plot-line" onclick="setPlotMode('line')">Line</button>
<button class="btn btn-info" id="btn-plot-scatter" onclick="setPlotMode('scatter')">Dot</button>
</div>
<div class="ctrl-sep"></div>
<div class="control-group">
<span class="control-label">Sort:</span>
<button class="btn btn-info active" id="btn-sort-selection" onclick="setSortMode('selection')">Order</button>
<button class="btn btn-info" id="btn-sort-name-asc" onclick="setSortMode('name-asc')">A→Z</button>
<button class="btn btn-info" id="btn-sort-name-desc" onclick="setSortMode('name-desc')">Z→A</button>
</div>
<div class="ctrl-sep"></div>
<div class="control-group">
<button class="btn btn-success" onclick="downloadCSV()">⬇ CSV</button>
<button class="btn btn-danger" onclick="clearData()">🗑 Clear</button>
</div>
</div>
<div class="stats-bar">
<span>Points:<strong id="data-point-count">0</strong></span>
<span>Time:<strong id="recording-time">0s</strong></span>
<span>Msgs:<strong id="msg-received">0</strong></span>
</div>
<div class="graphs" id="graphs"></div>
<script>
let ws;
let charts = {};
let graphing = false;
let startTime = 0;
let selectedSignals = [];
let dbcData = {};
let lastTimestamps = {};
let sortMode = 'selection';
const MAX_DATA_POINTS = 300;
let scaleMode = 'index';
let rangeMode = '10s';
let totalMsgReceived = 0;
let lastCanCounts = {};
let lastSignalTimes = {};
let plotMode = 'line'; // ★ 'line' | 'scatter'
const COLORS = [
{line: '#FF6384', fill: 'rgba(255, 99, 132, 0.2)'},
{line: '#36A2EB', fill: 'rgba(54, 162, 235, 0.2)'},
{line: '#FFCE56', fill: 'rgba(255, 206, 86, 0.2)'},
{line: '#4BC0C0', fill: 'rgba(75, 192, 192, 0.2)'},
{line: '#9966FF', fill: 'rgba(153, 102, 255, 0.2)'},
{line: '#FF9F40', fill: 'rgba(255, 159, 64, 0.2)'},
{line: '#FF6384', fill: 'rgba(255, 99, 132, 0.2)'},
{line: '#4BC0C0', fill: 'rgba(75, 192, 192, 0.2)'},
{line: '#FFCE56', fill: 'rgba(255, 206, 86, 0.2)'},
{line: '#9966FF', fill: 'rgba(153, 102, 255, 0.2)'},
{line: '#36A2EB', fill: 'rgba(54, 162, 235, 0.2)'},
{line: '#FF9F40', fill: 'rgba(255, 159, 64, 0.2)'},
{line: '#E74C3C', fill: 'rgba(231, 76, 60, 0.2)'},
{line: '#3498DB', fill: 'rgba(52, 152, 219, 0.2)'},
{line: '#2ECC71', fill: 'rgba(46, 204, 113, 0.2)'},
{line: '#F39C12', fill: 'rgba(243, 156, 18, 0.2)'},
{line: '#9B59B6', fill: 'rgba(155, 89, 182, 0.2)'},
{line: '#1ABC9C', fill: 'rgba(26, 188, 156, 0.2)'},
{line: '#E67E22', fill: 'rgba(230, 126, 34, 0.2)'},
{line: '#95A5A6', fill: 'rgba(149, 165, 166, 0.2)'}
];
class SimpleChart {
constructor(canvas, signal, colorIndex) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.signal = signal;
this.data = [];
this.times = [];
this.labels = [];
this.rawValues = [];
this.colors = COLORS[colorIndex % COLORS.length];
this.currentValue = 0;
this.currentText = '';
this.resizeCanvas();
window.addEventListener('resize', () => this.resizeCanvas());
}
resizeCanvas() {
const rect = this.canvas.getBoundingClientRect();
if (rect.width === 0) return;
const dpr = window.devicePixelRatio || 1;
this.canvas.width = rect.width * dpr;
this.canvas.height = rect.height * dpr;
// ★ 버그수정: scale() 누적 → setTransform() 으로 항상 초기화
this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
this.width = rect.width;
this.height = rect.height;
this.draw();
}
addData(value, time) {
this.data.push(value);
this.times.push(parseFloat(time));
this.labels.push(time);
this.rawValues.push(value);
this.currentValue = value;
if (this.signal.valueTable && this.signal.valueTable[value] !== undefined) {
this.currentText = this.signal.valueTable[value];
} else {
this.currentText = '';
}
if (scaleMode === 'index' && this.data.length > MAX_DATA_POINTS) {
this.data.shift();
this.times.shift();
this.labels.shift();
this.rawValues.shift();
}
}
// ⭐ 배치 데이터 추가 (500ms 동안 받은 모든 데이터)
addDataBatch(values, times) {
values.forEach((value, index) => {
this.addData(value, times[index]);
});
// 배치 추가 후 한 번만 그리기
this.draw();
}
getValueText(value) {
if (this.signal.valueTable && this.signal.valueTable[value] !== undefined) {
return this.signal.valueTable[value];
}
return value.toFixed(2);
}
draw() {
const ctx = this.ctx;
const W = this.width, H = this.height;
if (!W || !H) return;
const PAD_L = 52, PAD_R = 8, PAD_T = 12, PAD_B = 28;
const gW = W - PAD_L - PAD_R;
const gH = H - PAD_T - PAD_B;
// 배경
ctx.fillStyle = '#111827';
ctx.fillRect(0, 0, W, H);
// ★ 빈 데이터 상태 표시
if (this.data.length === 0) {
ctx.fillStyle = '#374151';
ctx.font = '12px monospace';
ctx.textAlign = 'center';
ctx.fillText('Waiting for data...', W / 2, H / 2);
return;
}
// ── 표시할 데이터 슬라이스 계산 ──
let displayData = [], displayTimes = [], displayLabels = [];
const windowSec = rangeMode === '30s' ? 30 : 10;
if (rangeMode === 'all') {
displayData = [...this.data];
displayTimes = [...this.times];
displayLabels = [...this.labels];
} else if (scaleMode === 'time') {
// time 모드: 시간 기준으로 window 필터
const latest = this.times[this.times.length - 1];
const cutoff = latest - windowSec;
for (let i = 0; i < this.times.length; i++) {
if (this.times[i] >= cutoff) {
displayData.push(this.data[i]);
displayTimes.push(this.times[i]);
displayLabels.push(this.labels[i]);
}
}
} else {
// ★ index 모드: 최근 N개만 표시
const N = rangeMode === '30s' ? 150 : 60;
const start = Math.max(0, this.data.length - N);
displayData = this.data.slice(start);
displayTimes = this.times.slice(start);
displayLabels = this.labels.slice(start);
}
if (displayData.length === 0) return;
const minValue = Math.min(...displayData);
const maxValue = Math.max(...displayData);
const range = maxValue - minValue || 1;
// ── Y 그리드 ──
const GRID_Y = 4;
ctx.lineWidth = 0.5;
for (let i = 0; i <= GRID_Y; i++) {
const y = PAD_T + (gH / GRID_Y) * i;
ctx.strokeStyle = (i === GRID_Y) ? '#2d3748' : '#1a2035';
ctx.beginPath(); ctx.moveTo(PAD_L, y); ctx.lineTo(PAD_L + gW, y); ctx.stroke();
// Y 라벨
const v = maxValue - (range / GRID_Y) * i;
let label = '';
if (this.signal.valueTable) {
const rv = Math.round(v);
label = (this.signal.valueTable[rv] !== undefined)
? String(this.signal.valueTable[rv]).substring(0, 7)
: v.toFixed(1);
} else {
label = Math.abs(v) < 100 ? v.toFixed(2) : v.toFixed(0);
}
ctx.fillStyle = '#6b7280';
ctx.font = '9px monospace';
ctx.textAlign = 'right';
ctx.fillText(label, PAD_L - 3, y + 3);
}
// ── X 그리드 ──
for (let i = 0; i <= 4; i++) {
const x = PAD_L + (gW / 4) * i;
ctx.strokeStyle = '#1a2035';
ctx.lineWidth = 0.5;
ctx.beginPath(); ctx.moveTo(x, PAD_T); ctx.lineTo(x, PAD_T + gH); ctx.stroke();
}
// ── 축선 ──
ctx.strokeStyle = '#2d3748';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(PAD_L, PAD_T);
ctx.lineTo(PAD_L, PAD_T + gH);
ctx.lineTo(PAD_L + gW, PAD_T + gH);
ctx.stroke();
// ── 좌표 변환 함수 ──
let minTime, timeRange;
if (scaleMode === 'time' && displayTimes.length > 1) {
minTime = displayTimes[0];
timeRange = displayTimes[displayTimes.length - 1] - minTime || 1;
}
const xOf = (i) => {
if (scaleMode === 'time' && displayTimes.length > 1) {
return PAD_L + ((displayTimes[i] - minTime) / timeRange) * gW;
}
// ★ 버그수정: MAX_DATA_POINTS 고정값 대신 실제 표시 데이터 개수 사용
return PAD_L + (displayData.length > 1 ? (i / (displayData.length - 1)) * gW : 0);
};
const yOf = (v) => PAD_T + gH - ((v - minValue) / range) * gH;
const lineColor = this.colors.line;
// ── Fill 영역 ──
ctx.beginPath();
ctx.moveTo(xOf(0), PAD_T + gH);
for (let i = 0; i < displayData.length; i++) ctx.lineTo(xOf(i), yOf(displayData[i]));
ctx.lineTo(xOf(displayData.length - 1), PAD_T + gH);
ctx.closePath();
// fill 색상: line 색에 알파 추가
ctx.fillStyle = this.colors.fill;
ctx.fill();
// ── Line 또는 Scatter ──
if (plotMode === 'line' && displayData.length > 1) {
// ★ 라인 그리기
ctx.strokeStyle = lineColor;
ctx.lineWidth = 1.8;
ctx.lineJoin = 'round';
ctx.beginPath();
ctx.moveTo(xOf(0), yOf(displayData[0]));
for (let i = 1; i < displayData.length; i++) {
ctx.lineTo(xOf(i), yOf(displayData[i]));
}
ctx.stroke();
}
// 점 그리기
for (let i = 0; i < displayData.length; i++) {
const isLast = (i === displayData.length - 1);
if (plotMode === 'scatter' || isLast) {
const r = isLast ? 4.5 : 2.5;
ctx.fillStyle = isLast ? '#ffffff' : lineColor;
ctx.strokeStyle = lineColor;
ctx.lineWidth = isLast ? 1.5 : 0;
ctx.beginPath();
ctx.arc(xOf(i), yOf(displayData[i]), r, 0, Math.PI * 2);
ctx.fill();
if (isLast) ctx.stroke();
}
}
// ── X 라벨 ──
ctx.fillStyle = '#6b7280';
ctx.font = '9px monospace';
ctx.textAlign = 'center';
if (displayLabels.length > 0) {
ctx.fillText(displayLabels[0] + 's', PAD_L, PAD_T + gH + 16);
ctx.fillText(displayLabels[displayLabels.length-1] + 's', PAD_L + gW, PAD_T + gH + 16);
if (displayLabels.length > 4) {
const mid = Math.floor(displayLabels.length / 2);
ctx.fillText(displayLabels[mid] + 's', PAD_L + gW * 0.5, PAD_T + gH + 16);
}
}
}
}
function initWebSocket() {
const hostname = window.location.hostname;
ws = new WebSocket('ws://' + hostname + ':81');
ws.onopen = function() {
console.log('WebSocket connected');
updateStatus('Connected', false);
};
ws.onclose = function() {
console.log('WebSocket disconnected');
updateStatus('Disconnected', true);
setTimeout(initWebSocket, 3000);
};
ws.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
// ★★★ 핵심 수정: 'update' 타입도 처리
if (graphing) {
if (data.type === 'canBatch') {
processCANData(data.messages);
} else if (data.type === 'update' || data.type === 'status') {
// 서버가 보내는 update 타입의 messages 배열 처리
if (data.messages && data.messages.length > 0) {
processCANDataFromUpdate(data.messages);
}
}
}
} catch(e) {
console.error('Error:', e);
}
};
}
function updateStatus(text, isError) {
const el = document.getElementById('status-pill');
if (!el) return;
el.textContent = text;
el.className = 'status' + (isError ? ' disconnected' : '');
}
function loadData() {
try {
const signals = localStorage.getItem('selected_signals');
const dbc = localStorage.getItem('dbc_content');
const savedSortMode = localStorage.getItem('sort_mode');
if (!signals || !dbc) {
alert('No signals selected. Please select signals first.');
window.close();
return false;
}
if (savedSortMode) {
sortMode = savedSortMode;
}
selectedSignals = JSON.parse(signals);
dbcData = {messages: {}};
selectedSignals.forEach(sig => {
if (!dbcData.messages[sig.messageId]) {
dbcData.messages[sig.messageId] = {
id: sig.messageId,
signals: []
};
}
dbcData.messages[sig.messageId].signals.push(sig);
});
console.log('Loaded', selectedSignals.length, 'signals');
selectedSignals.forEach(sig => {
if (sig.valueTable) {
console.log('Signal with Value Table:', sig.name, sig.valueTable);
}
});
return true;
} catch(e) {
console.error('Failed to load data:', e);
alert('Failed to load signal data');
window.close();
return false;
}
}
function sortSignalsForDisplay() {
if (sortMode === 'name-asc') {
return [...selectedSignals].sort((a, b) => a.name.localeCompare(b.name));
} else if (sortMode === 'name-desc') {
return [...selectedSignals].sort((a, b) => b.name.localeCompare(a.name));
} else {
return selectedSignals;
}
}
function setSortMode(mode) {
sortMode = mode;
document.querySelectorAll('[id^="btn-sort-"]').forEach(btn => btn.classList.remove('active'));
document.getElementById('btn-sort-' + mode).classList.add('active');
// ★ 버그수정: createGraphs() 호출 시 데이터 초기화 문제
// → 기존 차트 데이터를 보존한 채로 DOM 순서만 재배열
const graphsDiv = document.getElementById('graphs');
const oldCharts = Object.assign({}, charts);
const origSignals = [...selectedSignals];
const sorted = sortSignalsForDisplay();
graphsDiv.innerHTML = '';
charts = {};
sorted.forEach((signal, newIdx) => {
const origIdx = origSignals.findIndex(s =>
s.name === signal.name && s.messageId === signal.messageId);
const container = document.createElement('div');
container.className = 'graph-container';
const canvas = document.createElement('canvas');
canvas.id = 'chart-' + newIdx;
container.innerHTML =
'<div class="graph-header">' +
'<div class="graph-title">' + signal.name +
' <span style="color:#6b7280;font-size:0.85em;">(0x' + signal.messageId.toString(16).toUpperCase() + ')</span>' +
(signal.unit ? ' <span style="color:#6b7280;font-size:0.85em;">[' + signal.unit + ']</span>' : '') + '</div>' +
'<div class="graph-value" id="value-' + newIdx + '">-</div>' +
'</div>';
container.appendChild(canvas);
graphsDiv.appendChild(container);
const chart = new SimpleChart(canvas, signal, newIdx);
// 기존 데이터 복사
if (origIdx !== -1 && oldCharts[origIdx]) {
chart.data = [...oldCharts[origIdx].data];
chart.times = [...oldCharts[origIdx].times];
chart.labels = [...oldCharts[origIdx].labels];
chart.rawValues = [...(oldCharts[origIdx].rawValues || [])];
chart.currentValue = oldCharts[origIdx].currentValue;
chart.currentText = oldCharts[origIdx].currentText;
}
charts[newIdx] = chart;
chart.draw();
// 현재 값 표시 복원
const vEl = document.getElementById('value-' + newIdx);
if (vEl && chart.currentValue !== undefined && chart.currentValue !== null) {
if (chart.currentText) {
vEl.textContent = chart.currentText;
} else {
vEl.textContent = chart.currentValue.toFixed(2) + (signal.unit ? ' ' + signal.unit : '');
}
}
});
console.log('Sort mode changed to:', mode, '(data preserved)');
}
function createGraphs() {
const graphsDiv = document.getElementById('graphs');
graphsDiv.innerHTML = '';
charts = {};
const sortedSignals = sortSignalsForDisplay();
sortedSignals.forEach((signal, index) => {
const container = document.createElement('div');
container.className = 'graph-container';
const canvas = document.createElement('canvas');
canvas.id = 'chart-' + index;
container.innerHTML =
'<div class="graph-header">' +
'<div class="graph-title">' + signal.name +
' <span style="color:#6b7280;font-size:0.85em;">(0x' + signal.messageId.toString(16).toUpperCase() + ')</span>' +
(signal.unit ? ' <span style="color:#6b7280;font-size:0.85em;">[' + signal.unit + ']</span>' : '') + '</div>' +
'<div class="graph-value" id="value-' + index + '">-</div>' +
'</div>';
container.appendChild(canvas);
graphsDiv.appendChild(container);
charts[index] = new SimpleChart(canvas, signal, index);
});
document.getElementById('graph-count').textContent = sortedSignals.length;
}
function startGraphing() {
if (!graphing) {
graphing = true;
startTime = Date.now();
lastTimestamps = {};
document.getElementById('btn-start').classList.add('active');
document.getElementById('btn-stop').classList.remove('active');
updateStatus('Recording', false);
}
}
function stopGraphing() {
graphing = false;
document.getElementById('btn-start').classList.remove('active');
document.getElementById('btn-stop').classList.add('active');
updateStatus('Paused', false);
}
function setScaleMode(mode) {
scaleMode = mode;
document.getElementById('btn-index-mode').classList.toggle('active', mode === 'index');
document.getElementById('btn-time-mode').classList.toggle('active', mode === 'time');
Object.values(charts).forEach(chart => chart.draw());
}
function setRangeMode(mode) {
rangeMode = mode;
['10s','30s','all'].forEach(m => {
const el = document.getElementById('btn-range-' + m);
if (el) el.classList.toggle('active', m === mode);
});
Object.values(charts).forEach(chart => chart.draw());
}
// ★ 신규: Plot 모드 전환 (line / scatter)
function setPlotMode(mode) {
plotMode = mode;
document.getElementById('btn-plot-line').classList.toggle('active', mode === 'line');
document.getElementById('btn-plot-scatter').classList.toggle('active', mode === 'scatter');
Object.values(charts).forEach(chart => chart.draw());
}
// ★★★ 새로운 함수: update 타입 메시지 처리
// 서버가 보내는 형식: {id: 숫자, dlc: 숫자, data: [배열], count: 숫자}
// ★★★ count 차이만큼 배치로 데이터 추가 (500ms 동안 받은 모든 신호)
function processCANDataFromUpdate(messages) {
const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);
const sortedSignals = sortSignalsForDisplay();
// ⭐ 신호별로 데이터를 모을 배치 객체
const signalBatches = {};
sortedSignals.forEach((signal, index) => {
signalBatches[index] = {
values: [],
times: []
};
});
let processedCount = 0;
messages.forEach(canMsg => {
// id가 숫자로 오는 경우 처리
let msgId = canMsg.id;
if (typeof msgId === 'string') {
msgId = parseInt(msgId.replace('0x', ''), 16);
}
// Extended CAN ID 처리 (bit 31 제거)
if (msgId & 0x80000000) {
msgId = msgId & 0x1FFFFFFF;
}
// ★ count 차이 계산 (500ms 동안 몇 개의 메시지가 왔는지)
const prevCount = lastCanCounts[msgId] || 0;
const currentCount = canMsg.count || 0;
const countDiff = currentCount - prevCount;
if (countDiff <= 0) {
// count가 증가하지 않았으면 스킵
return;
}
// count 업데이트
lastCanCounts[msgId] = currentCount;
totalMsgReceived += countDiff;
// data가 배열로 오는 경우 HEX 문자열로 변환
let hexData = '';
if (Array.isArray(canMsg.data)) {
hexData = canMsg.data.map(b => b.toString(16).padStart(2, '0')).join('');
} else if (typeof canMsg.data === 'string') {
hexData = canMsg.data.replace(/\s/g, '');
}
sortedSignals.forEach((signal, index) => {
if (signal.messageId === msgId && charts[index]) {
try {
const value = decodeSignalFromHex(signal, hexData);
// ⭐ 신호별 시간 간격 계산
const signalKey = `${msgId}_${signal.name}`;
const lastTime = lastSignalTimes[signalKey] || 0;
const currentTime = parseFloat(elapsedTime);
const timeDelta = currentTime - lastTime;
// ⭐ 배치에 데이터 추가 (count 차이만큼, 각각 고유한 시간)
// 예: 10ms 주기 신호가 500ms 동안 50개 왔으면
// countDiff = 50
// 각 데이터를 시간 간격에 맞춰 분산
for (let i = 0; i < countDiff; i++) {
signalBatches[index].values.push(value);
// ⭐ 시간 분산: 500ms 동안 50개면 10ms 간격
const timeOffset = (timeDelta / countDiff) * i;
const dataTime = (lastTime + timeOffset).toFixed(3);
signalBatches[index].times.push(dataTime);
}
// 마지막 시간 업데이트
lastSignalTimes[signalKey] = currentTime;
const valueDiv = document.getElementById('value-' + index);
if (valueDiv) {
if (signal.valueTable && signal.valueTable[value] !== undefined) {
valueDiv.textContent = signal.valueTable[value];
} else {
valueDiv.textContent = value.toFixed(2) + (signal.unit ? ' ' + signal.unit : '');
}
}
processedCount += countDiff;
} catch(e) {
console.error('Error decoding signal ' + signal.name + ':', e);
}
}
});
});
// ⭐ 배치 데이터를 차트에 한 번에 추가
sortedSignals.forEach((signal, index) => {
if (charts[index] && signalBatches[index].values.length > 0) {
charts[index].addDataBatch(
signalBatches[index].values,
signalBatches[index].times
);
}
});
if (processedCount > 0) {
console.log('Added', processedCount, 'new data points from update (batch mode)');
}
updateStatistics();
}
// 기존 canBatch 처리 함수 (문자열 형식 데이터용)
function processCANData(messages) {
const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);
const sortedSignals = sortSignalsForDisplay();
console.log('Processing', messages.length, 'messages at time', elapsedTime + 's');
let processedCount = 0;
totalMsgReceived += messages.length;
messages.forEach(canMsg => {
const idStr = (canMsg.id || '').toString().replace(/\s/g, '').toUpperCase();
let msgId = parseInt(idStr.replace('0X', ''), 16);
if (msgId & 0x80000000) {
msgId = msgId & 0x1FFFFFFF;
}
const timestamp = canMsg.timestamp;
sortedSignals.forEach((signal, index) => {
if (signal.messageId === msgId && charts[index]) {
try {
const value = decodeSignal(signal, canMsg.data);
charts[index].addData(value, elapsedTime);
const valueDiv = document.getElementById('value-' + index);
if (valueDiv) {
if (signal.valueTable && signal.valueTable[value] !== undefined) {
valueDiv.textContent = signal.valueTable[value];
} else {
valueDiv.textContent = value.toFixed(2) + (signal.unit ? ' ' + signal.unit : '');
}
}
processedCount++;
} catch(e) {
console.error('Error decoding signal ' + signal.name + ':', e);
}
}
});
});
if (processedCount > 0) {
console.log('Added', processedCount, 'new data points');
}
updateStatistics();
}
function updateStatistics() {
let totalDataPoints = 0;
Object.values(charts).forEach(chart => {
totalDataPoints += chart.data.length;
});
document.getElementById('data-point-count').textContent = totalDataPoints;
document.getElementById('msg-received').textContent = totalMsgReceived;
const recordingTime = ((Date.now() - startTime) / 1000).toFixed(1);
document.getElementById('recording-time').textContent = recordingTime + 's';
}
// ★ HEX 문자열에서 바이트 배열로 변환 후 디코딩
function decodeSignalFromHex(signal, hexData) {
const bytes = [];
const cleanHex = hexData.toUpperCase();
for (let i = 0; i < cleanHex.length && i < 16; i += 2) {
bytes.push(parseInt(cleanHex.substring(i, i + 2), 16));
}
while (bytes.length < 8) bytes.push(0);
return decodeSignalFromBytes(signal, bytes);
}
function decodeSignal(signal, hexData) {
const bytes = [];
if (typeof hexData === 'string') {
const cleanHex = hexData.replace(/\s/g, '').toUpperCase();
for (let i = 0; i < cleanHex.length && i < 16; i += 2) {
bytes.push(parseInt(cleanHex.substring(i, i + 2), 16));
}
} else if (Array.isArray(hexData)) {
bytes.push(...hexData);
}
while (bytes.length < 8) bytes.push(0);
return decodeSignalFromBytes(signal, bytes);
}
function decodeSignalFromBytes(signal, bytes) {
let rawValue = 0;
if (signal.byteOrder === 'intel') {
for (let i = 0; i < signal.bitLength; i++) {
const bitPos = signal.startBit + i;
const byteIdx = Math.floor(bitPos / 8);
const bitIdx = bitPos % 8;
if (byteIdx < bytes.length) {
const bit = (bytes[byteIdx] >> bitIdx) & 1;
rawValue |= (bit << i);
}
}
} else {
for (let i = 0; i < signal.bitLength; i++) {
const bitPos = signal.startBit - i;
const byteIdx = Math.floor(bitPos / 8);
const bitIdx = 7 - (bitPos % 8);
if (byteIdx < bytes.length && byteIdx >= 0) {
const bit = (bytes[byteIdx] >> bitIdx) & 1;
rawValue |= (bit << (signal.bitLength - 1 - i));
}
}
}
if (signal.signed && (rawValue & (1 << (signal.bitLength - 1)))) {
rawValue -= (1 << signal.bitLength);
}
return rawValue * signal.factor + signal.offset;
}
function downloadCSV() {
if (Object.keys(charts).length === 0) {
alert('No data to download!');
return;
}
let csvContent = 'Time(s)';
const sortedSignals = sortSignalsForDisplay();
sortedSignals.forEach(signal => {
const unit = signal.unit ? ' [' + signal.unit + ']' : '';
csvContent += ',' + signal.name + unit;
if (signal.valueTable) {
csvContent += ',' + signal.name + '_Text';
}
});
csvContent += '\n';
let maxLength = 0;
Object.values(charts).forEach(chart => {
if (chart.labels.length > maxLength) {
maxLength = chart.labels.length;
}
});
for (let i = 0; i < maxLength; i++) {
let row = '';
let timeValue = '';
sortedSignals.forEach((signal, index) => {
const chart = charts[index];
if (chart && chart.labels[i] !== undefined) {
if (timeValue === '') {
timeValue = chart.labels[i];
}
const value = chart.data[i];
row += ',' + value.toFixed(6);
if (signal.valueTable) {
const text = signal.valueTable[value] !== undefined ?
signal.valueTable[value] : '';
row += ',"' + text + '"';
}
} else {
row += ',';
if (signal.valueTable) {
row += ',';
}
}
});
if (timeValue !== '') {
csvContent += timeValue + row + '\n';
}
}
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
link.setAttribute('href', url);
link.setAttribute('download', 'can_signals_' + timestamp + '.csv');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log('CSV downloaded with ' + maxLength + ' data points');
}
function clearData() {
if (!confirm('Clear all recorded data? This cannot be undone.')) {
return;
}
Object.values(charts).forEach(chart => {
chart.data = [];
chart.times = [];
chart.labels = [];
chart.rawValues = [];
chart.currentValue = 0;
chart.currentText = '';
chart.draw();
});
lastTimestamps = {};
lastCanCounts = {};
lastSignalTimes = {}; // ★ 버그수정: 시간 계산 리셋
startTime = Date.now();
totalMsgReceived = 0;
updateStatistics();
console.log('All data cleared');
}
if (loadData()) {
createGraphs();
initWebSocket();
startGraphing();
}
</script>
</body>
</html>
)rawliteral";
#endif