@@ -201,33 +218,167 @@ const char graph_html[] PROGMEM = R"rawliteral(
let selectedSignals = [];
let charts = {};
let graphing = false;
+ let startTime = 0;
const MAX_SIGNALS = 6;
const MAX_DATA_POINTS = 60;
- const COLORS = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'];
+ const COLORS = [
+ {line: '#FF6384', fill: 'rgba(255, 99, 132, 0.1)'},
+ {line: '#36A2EB', fill: 'rgba(54, 162, 235, 0.1)'},
+ {line: '#FFCE56', fill: 'rgba(255, 206, 86, 0.1)'},
+ {line: '#4BC0C0', fill: 'rgba(75, 192, 192, 0.1)'},
+ {line: '#9966FF', fill: 'rgba(153, 102, 255, 0.1)'},
+ {line: '#FF9F40', fill: 'rgba(255, 159, 64, 0.1)'}
+ ];
- // DBC 데이터를 localStorage에 저장
- function saveDBCToStorage() {
- try {
- localStorage.setItem('dbcData', JSON.stringify(dbcData));
- localStorage.setItem('dbcFileName', document.getElementById('dbc-status').textContent);
- } catch(e) {
- console.log('Storage not available');
+ // 커스텀 차트 클래스
+ class SimpleChart {
+ constructor(canvas, signal, colorIndex) {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d');
+ this.signal = signal;
+ this.data = [];
+ this.labels = [];
+ this.colors = COLORS[colorIndex % COLORS.length];
+ this.currentValue = 0;
+
+ // Canvas 크기 설정
+ this.resizeCanvas();
+ window.addEventListener('resize', () => this.resizeCanvas());
}
- }
-
- // 저장된 DBC 데이터 불러오기
- function loadDBCFromStorage() {
- try {
- const savedDBC = localStorage.getItem('dbcData');
- const savedFileName = localStorage.getItem('dbcFileName');
- if (savedDBC && savedFileName && savedFileName !== 'No file loaded') {
- dbcData = JSON.parse(savedDBC);
- document.getElementById('dbc-status').textContent = savedFileName;
- displaySignals();
- showStatus('DBC file restored: ' + savedFileName, 'success');
+
+ resizeCanvas() {
+ const rect = this.canvas.getBoundingClientRect();
+ this.canvas.width = rect.width * window.devicePixelRatio;
+ this.canvas.height = rect.height * window.devicePixelRatio;
+ this.ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
+ this.width = rect.width;
+ this.height = rect.height;
+ this.draw();
+ }
+
+ addData(value, label) {
+ this.data.push(value);
+ this.labels.push(label);
+ this.currentValue = value;
+
+ if (this.data.length > MAX_DATA_POINTS) {
+ this.data.shift();
+ this.labels.shift();
+ }
+
+ this.draw();
+ }
+
+ draw() {
+ if (this.data.length === 0) return;
+
+ const ctx = this.ctx;
+ const padding = 40;
+ const graphWidth = this.width - padding * 2;
+ const graphHeight = this.height - padding * 2;
+
+ // 배경 클리어
+ ctx.clearRect(0, 0, this.width, this.height);
+
+ // 데이터 범위 계산
+ const minValue = Math.min(...this.data);
+ const maxValue = Math.max(...this.data);
+ const range = maxValue - minValue || 1;
+
+ // 축 그리기
+ ctx.strokeStyle = '#ddd';
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.moveTo(padding, padding);
+ ctx.lineTo(padding, this.height - padding);
+ ctx.lineTo(this.width - padding, this.height - padding);
+ ctx.stroke();
+
+ // Y축 라벨
+ ctx.fillStyle = '#666';
+ ctx.font = '11px Arial';
+ ctx.textAlign = 'right';
+ ctx.fillText(maxValue.toFixed(2), padding - 5, padding + 5);
+ ctx.fillText(minValue.toFixed(2), padding - 5, this.height - padding);
+
+ // X축 라벨 (시간 - 초 단위)
+ ctx.textAlign = 'center';
+ ctx.fillStyle = '#666';
+ ctx.font = '10px Arial';
+ if (this.labels.length > 0) {
+ // 첫 번째와 마지막 시간 표시
+ ctx.fillText(this.labels[0] + 's', padding, this.height - padding + 15);
+ if (this.labels.length > 1) {
+ const lastIdx = this.labels.length - 1;
+ ctx.fillText(this.labels[lastIdx] + 's',
+ padding + (graphWidth / (MAX_DATA_POINTS - 1)) * lastIdx,
+ this.height - padding + 15);
+ }
+ }
+
+ // X축 타이틀
+ ctx.fillText('Time (sec)', this.width / 2, this.height - 5);
+
+ // 그리드 라인
+ ctx.strokeStyle = '#f0f0f0';
+ ctx.lineWidth = 1;
+ for (let i = 1; i < 5; i++) {
+ const y = padding + (graphHeight / 5) * i;
+ ctx.beginPath();
+ ctx.moveTo(padding, y);
+ ctx.lineTo(this.width - padding, y);
+ ctx.stroke();
+ }
+
+ if (this.data.length < 2) return;
+
+ // 영역 채우기
+ ctx.fillStyle = this.colors.fill;
+ ctx.beginPath();
+ ctx.moveTo(padding, this.height - padding);
+
+ for (let i = 0; i < this.data.length; i++) {
+ const x = padding + (graphWidth / (MAX_DATA_POINTS - 1)) * i;
+ const y = this.height - padding - ((this.data[i] - minValue) / range) * graphHeight;
+ if (i === 0) {
+ ctx.lineTo(x, y);
+ } else {
+ ctx.lineTo(x, y);
+ }
+ }
+
+ ctx.lineTo(padding + (graphWidth / (MAX_DATA_POINTS - 1)) * (this.data.length - 1), this.height - padding);
+ ctx.closePath();
+ ctx.fill();
+
+ // 선 그리기
+ ctx.strokeStyle = this.colors.line;
+ ctx.lineWidth = 2;
+ ctx.beginPath();
+
+ for (let i = 0; i < this.data.length; i++) {
+ const x = padding + (graphWidth / (MAX_DATA_POINTS - 1)) * i;
+ const y = this.height - padding - ((this.data[i] - minValue) / range) * graphHeight;
+
+ if (i === 0) {
+ ctx.moveTo(x, y);
+ } else {
+ ctx.lineTo(x, y);
+ }
+ }
+
+ ctx.stroke();
+
+ // 데이터 포인트
+ ctx.fillStyle = this.colors.line;
+ for (let i = 0; i < this.data.length; i++) {
+ const x = padding + (graphWidth / (MAX_DATA_POINTS - 1)) * i;
+ const y = this.height - padding - ((this.data[i] - minValue) / range) * graphHeight;
+
+ ctx.beginPath();
+ ctx.arc(x, y, 2, 0, Math.PI * 2);
+ ctx.fill();
}
- } catch(e) {
- console.log('Could not restore DBC');
}
}
@@ -236,18 +387,24 @@ const char graph_html[] PROGMEM = R"rawliteral(
ws.onopen = function() {
console.log('WebSocket connected');
+ showStatus('Connected', 'success');
};
ws.onclose = function() {
console.log('WebSocket disconnected');
+ showStatus('Disconnected - Reconnecting...', 'error');
setTimeout(initWebSocket, 3000);
};
ws.onmessage = function(event) {
- const data = JSON.parse(event.data);
-
- if (data.type === 'canBatch' && graphing) {
- processCANData(data.messages);
+ try {
+ const data = JSON.parse(event.data);
+
+ if (data.type === 'canBatch' && graphing) {
+ processCANData(data.messages);
+ }
+ } catch(e) {
+ console.error('Error parsing WebSocket data:', e);
}
};
}
@@ -261,11 +418,43 @@ const char graph_html[] PROGMEM = R"rawliteral(
const content = e.target.result;
parseDBCContent(content);
document.getElementById('dbc-status').textContent = file.name;
- saveDBCToStorage();
+
+ // DBC 파일 저장
+ saveDBCToLocalStorage(content, file.name);
};
reader.readAsText(file);
}
+ // DBC 파일을 localStorage에 저장
+ function saveDBCToLocalStorage(content, filename) {
+ try {
+ localStorage.setItem('dbc_content', content);
+ localStorage.setItem('dbc_filename', filename);
+ console.log('DBC saved to localStorage:', filename);
+ } catch(e) {
+ console.error('Failed to save DBC to localStorage:', e);
+ }
+ }
+
+ // localStorage에서 DBC 파일 복원
+ function loadDBCFromLocalStorage() {
+ try {
+ const content = localStorage.getItem('dbc_content');
+ const filename = localStorage.getItem('dbc_filename');
+
+ if (content && filename) {
+ parseDBCContent(content);
+ document.getElementById('dbc-status').textContent = filename + ' (restored)';
+ showStatus('DBC file restored: ' + filename, 'success');
+ console.log('DBC restored from localStorage:', filename);
+ return true;
+ }
+ } catch(e) {
+ console.error('Failed to load DBC from localStorage:', e);
+ }
+ return false;
+ }
+
function parseDBCContent(content) {
dbcData = {messages: {}};
const lines = content.split('\n');
@@ -274,7 +463,6 @@ const char graph_html[] PROGMEM = R"rawliteral(
for (let line of lines) {
line = line.trim();
- // BO_ 123 MessageName: 8 Vector__XXX 형식
if (line.startsWith('BO_ ')) {
const match = line.match(/BO_\s+(\d+)\s+(\w+)\s*:/);
if (match) {
@@ -284,7 +472,6 @@ const char graph_html[] PROGMEM = R"rawliteral(
dbcData.messages[id] = currentMessage;
}
}
- // SG_ SignalName : 0|16@1+ (1,0) [0|100] "unit" 형식
else if (line.startsWith('SG_ ') && currentMessage) {
const match = line.match(/SG_\s+(\w+)\s*:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,]+),([^)]+)\)\s*\[([^\]]+)\]\s*"([^"]*)"/);
if (match) {
@@ -364,6 +551,7 @@ const char graph_html[] PROGMEM = R"rawliteral(
}
graphing = true;
+ startTime = Date.now(); // 시작 시간 기록
createGraphs();
showStatus('Graphing ' + selectedSignals.length + ' signals', 'success');
}
@@ -385,60 +573,41 @@ const char graph_html[] PROGMEM = R"rawliteral(
const canvas = document.createElement('canvas');
canvas.id = 'chart-' + index;
- container.innerHTML = '
' + signal.name +
- ' (0x' + signal.messageId.toString(16).toUpperCase() + ')' +
- (signal.unit ? ' [' + signal.unit + ']' : '') + '
' +
- '
';
- container.querySelector('.graph-canvas').appendChild(canvas);
+ container.innerHTML =
+ '';
+
+ container.appendChild(canvas);
graphsDiv.appendChild(container);
- const ctx = canvas.getContext('2d');
- charts[index] = new Chart(ctx, {
- type: 'line',
- data: {
- labels: [],
- datasets: [{
- label: signal.name,
- data: [],
- borderColor: COLORS[index % COLORS.length],
- backgroundColor: COLORS[index % COLORS.length] + '33',
- tension: 0.4,
- fill: true
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- scales: {
- x: { display: true, title: { display: true, text: 'Time' }},
- y: { display: true, title: { display: true, text: signal.unit || 'Value' }}
- },
- animation: false
- }
- });
+ charts[index] = new SimpleChart(canvas, signal, index);
});
}
function processCANData(messages) {
- const now = new Date().toLocaleTimeString();
+ // 경과 시간 계산 (초 단위, 소수점 1자리)
+ const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);
messages.forEach(canMsg => {
- const msgId = parseInt(canMsg.id, 16);
+ const idStr = canMsg.id.replace(/\s/g, '').toUpperCase();
+ const msgId = parseInt(idStr, 16);
selectedSignals.forEach((signal, index) => {
if (signal.messageId === msgId && charts[index]) {
- const value = decodeSignal(signal, canMsg.data);
-
- const chart = charts[index];
- chart.data.labels.push(now);
- chart.data.datasets[0].data.push(value);
-
- if (chart.data.labels.length > MAX_DATA_POINTS) {
- chart.data.labels.shift();
- chart.data.datasets[0].data.shift();
+ try {
+ const value = decodeSignal(signal, canMsg.data);
+ charts[index].addData(value, elapsedTime);
+
+ const valueDiv = document.getElementById('value-' + index);
+ if (valueDiv) {
+ valueDiv.textContent = value.toFixed(2) + (signal.unit ? ' ' + signal.unit : '');
+ }
+ } catch(e) {
+ console.error('Error decoding signal', signal.name, ':', e);
}
-
- chart.update('none');
}
});
});
@@ -446,17 +615,22 @@ const char graph_html[] PROGMEM = R"rawliteral(
function decodeSignal(signal, hexData) {
const bytes = [];
- const parts = hexData.split(' ');
- for (let part of parts) {
- if (part.length === 2) {
- bytes.push(parseInt(part, 16));
+
+ 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));
}
}
+ while (bytes.length < 8) {
+ bytes.push(0);
+ }
+
let rawValue = 0;
if (signal.byteOrder === 'intel') {
- // Little Endian (Intel)
for (let i = 0; i < signal.bitLength; i++) {
const bitPos = signal.startBit + i;
const byteIdx = Math.floor(bitPos / 8);
@@ -468,7 +642,6 @@ const char graph_html[] PROGMEM = R"rawliteral(
}
}
} else {
- // Big Endian (Motorola)
for (let i = 0; i < signal.bitLength; i++) {
const bitPos = signal.startBit - i;
const byteIdx = Math.floor(bitPos / 8);
@@ -481,12 +654,13 @@ const char graph_html[] PROGMEM = R"rawliteral(
}
}
- // Signed 처리
if (signal.signed && (rawValue & (1 << (signal.bitLength - 1)))) {
rawValue -= (1 << signal.bitLength);
}
- return rawValue * signal.factor + signal.offset;
+ const physicalValue = rawValue * signal.factor + signal.offset;
+
+ return physicalValue;
}
function showStatus(message, type) {
@@ -526,15 +700,17 @@ const char graph_html[] PROGMEM = R"rawliteral(
reader.onload = function(ev) {
parseDBCContent(ev.target.result);
document.getElementById('dbc-status').textContent = file.name;
- saveDBCToStorage();
+
+ // DBC 파일 저장
+ saveDBCToLocalStorage(ev.target.result, file.name);
};
reader.readAsText(file);
}
});
- // 페이지 로드 시 저장된 DBC 복원
+ // 페이지 로드 시 localStorage에서 DBC 복원
window.addEventListener('load', function() {
- loadDBCFromStorage();
+ loadDBCFromLocalStorage();
});
initWebSocket();