00006 graph 로컬라이브러리 사용
esp32와 mcp2515로 can data 실시간 로깅(sd spi) 하는 프로그램 코드인데 로깅은 잘돼 하지만 그래프 웹페이지에서 변수를 선택한 후 start누르면 그래프가 실시간 그려지지 않아 실시간 그래프 그려지도록 데이터 수정해줘 ESP32가 인터넷에 연결되지 않은 상태라서 다른 방법 없을까? graph 웹페이지에서 dbc 넣은 다음 그래프 잘 출력되는데 그래프의 x축 에 대한 값 sec을 표현해주었으면 하고 다른페이지 이동 클릭한다음 graph 페이지 오면 넣었던 dbc가 없어져 다시 넣어야 하는데 넣었던 dbc는 다른 페이지 이동해도 유지할 수 있도록 수정해줘
This commit is contained in:
362
graph.h
362
graph.h
@@ -8,7 +8,6 @@ const char graph_html[] PROGMEM = R"rawliteral(
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<title>CAN Signal Graph</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
@@ -99,10 +98,33 @@ const char graph_html[] PROGMEM = R"rawliteral(
|
||||
padding: 15px;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 15px;
|
||||
border: 2px solid #e0e0e0;
|
||||
}
|
||||
.graph-canvas {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
.graph-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 2px solid #43cea2;
|
||||
}
|
||||
.graph-title {
|
||||
font-size: 1em;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
.graph-value {
|
||||
font-size: 1.2em;
|
||||
font-weight: 700;
|
||||
color: #185a9d;
|
||||
font-family: 'Courier New', monospace;
|
||||
}
|
||||
canvas {
|
||||
width: 100%;
|
||||
height: 250px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
.controls {
|
||||
@@ -142,13 +164,8 @@ const char graph_html[] PROGMEM = R"rawliteral(
|
||||
.header h1 { font-size: 1.5em; }
|
||||
.content { padding: 10px; }
|
||||
.signal-grid { grid-template-columns: 1fr; gap: 8px; }
|
||||
.signal-item { padding: 10px; }
|
||||
.graph-canvas { height: 250px; }
|
||||
canvas { height: 200px; }
|
||||
h2 { font-size: 1.1em; }
|
||||
.controls { gap: 5px; }
|
||||
.btn { padding: 8px 15px; font-size: 0.85em; }
|
||||
.nav a { padding: 8px 10px; font-size: 0.85em; }
|
||||
.upload-area { padding: 20px 15px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -156,7 +173,7 @@ const char graph_html[] PROGMEM = R"rawliteral(
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>CAN Signal Graph</h1>
|
||||
<p>Real-time Signal Visualization</p>
|
||||
<p>Real-time Signal Visualization (Offline Mode)</p>
|
||||
</div>
|
||||
|
||||
<div class="nav">
|
||||
@@ -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 = '<h3 style="font-size:1em;margin-bottom:10px;">' + signal.name +
|
||||
' (0x' + signal.messageId.toString(16).toUpperCase() + ')' +
|
||||
(signal.unit ? ' [' + signal.unit + ']' : '') + '</h3>' +
|
||||
'<div class="graph-canvas"></div>';
|
||||
container.querySelector('.graph-canvas').appendChild(canvas);
|
||||
container.innerHTML =
|
||||
'<div class="graph-header">' +
|
||||
'<div class="graph-title">' + signal.name + ' (0x' + signal.messageId.toString(16).toUpperCase() + ')' +
|
||||
(signal.unit ? ' [' + signal.unit + ']' : '') + '</div>' +
|
||||
'<div class="graph-value" id="value-' + index + '">-</div>' +
|
||||
'</div>';
|
||||
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user