첫 업로드

This commit is contained in:
2026-02-13 19:38:00 +00:00
commit 5503760555
5 changed files with 4621 additions and 0 deletions

1624
ESP32_CANFD_Logger.ino Normal file

File diff suppressed because it is too large Load Diff

888
canfd_graph.h Normal file
View File

@@ -0,0 +1,888 @@
#ifndef CANFD_GRAPH_H
#define CANFD_GRAPH_H
const char canfd_graph_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>CAN FD Signal Graph</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #f7931e 0%, #e85d04 100%);
min-height: 100vh;
padding: 10px;
}
.container {
max-width: 1600px;
margin: 0 auto;
background: white;
border-radius: 15px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #f7931e 0%, #e85d04 100%);
color: white;
padding: 20px;
text-align: center;
}
.header h1 { font-size: 1.8em; margin-bottom: 5px; }
/* ========== 통일된 네비게이션 ========== */
.nav {
background: #f8f9fa;
padding: 0;
border-bottom: 2px solid #e0e0e0;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.nav a {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 15px 20px;
text-decoration: none;
color: #666;
font-weight: 500;
font-size: 0.95em;
border-bottom: 3px solid transparent;
transition: all 0.3s;
white-space: nowrap;
min-width: 120px;
}
.nav a:hover {
background: #e9ecef;
color: #f7931e;
transform: translateY(-2px);
}
.nav a.active {
color: #e85d04;
border-bottom-color: #e85d04;
background: white;
font-weight: 600;
}
.content { padding: 15px; }
.dbc-upload {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-bottom: 15px;
}
.upload-area {
border: 3px dashed #f7931e;
border-radius: 10px;
padding: 30px 20px;
text-align: center;
cursor: pointer;
transition: all 0.3s;
}
.upload-area:hover { background: #fff8f0; border-color: #e85d04; }
.upload-area input { display: none; }
.signal-selector {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
margin-bottom: 15px;
}
.search-container {
margin-bottom: 15px;
position: relative;
}
.search-box {
width: 100%;
padding: 12px 12px 12px 40px;
border: 2px solid #f7931e;
border-radius: 8px;
font-size: 0.95em;
transition: all 0.3s;
}
.search-box:focus {
outline: none;
border-color: #e85d04;
box-shadow: 0 0 0 3px rgba(247, 147, 30, 0.1);
}
.search-icon {
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
color: #f7931e;
font-size: 1.2em;
}
.search-info {
margin-top: 8px;
padding: 8px 12px;
background: #fff3e0;
border-radius: 5px;
font-size: 0.85em;
color: #e85d04;
font-weight: 600;
}
.no-results {
text-align: center;
padding: 40px 20px;
color: white;
font-size: 0.95em;
}
.no-results-icon {
font-size: 3em;
margin-bottom: 10px;
opacity: 0.5;
}
.sort-controls {
display: flex;
gap: 10px;
margin-bottom: 15px;
align-items: center;
flex-wrap: wrap;
}
.sort-label {
font-weight: 600;
color: #333;
font-size: 0.9em;
}
.sort-btn {
padding: 8px 15px;
border: 2px solid #f7931e;
background: white;
border-radius: 5px;
font-size: 0.85em;
cursor: pointer;
transition: all 0.3s;
font-weight: 600;
}
.sort-btn:hover {
background: #fff8f0;
transform: translateY(-2px);
}
.sort-btn.active {
background: #f7931e;
color: white;
}
.signal-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 10px;
margin-top: 15px;
}
.signal-item {
background: white;
padding: 12px;
border-radius: 8px;
border: 2px solid #ddd;
cursor: pointer;
transition: all 0.3s;
}
.signal-item:hover { border-color: #f7931e; transform: translateY(-2px); }
.signal-item.selected { border-color: #e85d04; background: #fff3e0; }
.signal-name { font-weight: 600; color: #333; margin-bottom: 5px; font-size: 0.9em; }
.signal-info { font-size: 0.8em; color: #555; line-height: 1.4; }
.highlight {
background-color: #ffeb3b;
padding: 2px 0;
font-weight: 600;
}
.controls {
display: flex;
gap: 8px;
margin-bottom: 15px;
flex-wrap: wrap;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: 0.9em;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn-primary { background: linear-gradient(135deg, #f7931e 0%, #e85d04 100%); color: white; }
.btn-success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; }
.btn-danger { background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%); color: white; }
.btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
h2 {
color: #333;
margin: 20px 0 15px 0;
padding-bottom: 8px;
border-bottom: 3px solid #f7931e;
font-size: 1.3em;
}
.status { padding: 12px; background: #fff3cd; border-radius: 5px; margin-bottom: 15px; font-size: 0.9em; }
.status.success { background: #d4edda; color: #155724; }
.status.error { background: #f8d7da; color: #721c24; }
.selection-info {
background: #fff3e0;
padding: 12px 15px;
border-radius: 8px;
margin-bottom: 15px;
border-left: 4px solid #e85d04;
font-size: 0.9em;
color: #333;
}
.selection-info strong {
color: #e85d04;
}
/* ========== 반응형 디자인 ========== */
@media (max-width: 768px) {
body {
padding: 5px;
}
.container {
border-radius: 10px;
}
.header {
padding: 15px;
flex-direction: column;
text-align: center;
gap: 10px;
}
.header h1 {
font-size: 1.4em;
}
.nav {
padding: 5px;
}
.nav a {
padding: 12px 15px;
font-size: 0.85em;
}
.content {
padding: 15px;
}
.btn {
padding: 10px 20px;
font-size: 13px;
}
}
@media (min-width: 769px) and (max-width: 1024px) {
.header h1 {
font-size: 1.6em;
}
.nav a {
padding: 13px 18px;
font-size: 0.9em;
}
.content {
padding: 25px;
}
}
@media (min-width: 1025px) {
.content {
padding: 30px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🚀 CAN FD Signal Graph</h1>
<p>Real-time Signal Visualization (64-byte Support)</p>
</div>
<div class="nav">
<a href="/">📊 Dashboard</a>
<a href="/settings"> Settings</a>
<a href="/graph" class="active">📈 Graph</a>
<a href="/graph-view">📊 Graph View</a>
</div>
<div class="content">
<div id="status" class="status" style="display:none;"></div>
<h2>Upload DBC File</h2>
<div class="dbc-upload">
<div class="upload-area" onclick="document.getElementById('dbc-file').click()">
<input type="file" id="dbc-file" accept=".dbc" onchange="loadDBCFile(event)">
<p style="font-size: 1.1em; margin-bottom: 8px;">Click to upload DBC (CAN FD supported)</p>
<p style="color: black; font-size: 0.85em;" id="dbc-status">No file loaded</p>
</div>
</div>
<div id="signal-section" style="display:none;">
<h2>Select Signals (Max 20)</h2>
<div class="selection-info">
<strong>Selected: <span id="selected-count">0</span> / 20</strong>
</div>
<div class="controls">
<button class="btn btn-success" onclick="startGraphing()">Start</button>
<button class="btn btn-danger" onclick="stopGraphing()">Stop</button>
<button class="btn btn-primary" onclick="clearSelection()">Clear</button>
<button class="btn btn-primary" onclick="debugDBCInfo()">Debug Info</button>
</div>
<div class="signal-selector">
<div class="search-container">
<span class="search-icon">🔍</span>
<input type="text"
id="search-box"
class="search-box"
placeholder="Search by signal name, CAN ID, message name, or unit..."
oninput="filterSignals()">
<div id="search-info" class="search-info" style="display:none;"></div>
</div>
<div class="sort-controls">
<span class="sort-label">Sort by:</span>
<button class="sort-btn active" id="sort-selection" onclick="setSortMode('selection')">Selection Order</button>
<button class="sort-btn" id="sort-name-asc" onclick="setSortMode('name-asc')">Name (AZ)</button>
<button class="sort-btn" id="sort-name-desc" onclick="setSortMode('name-desc')">Name (ZA)</button>
</div>
<div id="signal-list" class="signal-grid"></div>
</div>
<div style="background: #fff3e0; padding: 15px; border-radius: 8px; margin-top: 15px; border-left: 4px solid #e85d04;">
<p style="color: #333; font-size: 0.9em; margin: 0;">
<strong> CAN FD Info:</strong> Supports signals up to 64 bytes (512 bits).
Click "Start" to open real-time graphs.
</p>
</div>
</div>
</div>
</div>
<script>
let ws;
let dbcData = {};
let selectedSignals = [];
let allSignals = [];
let filteredSignals = [];
let sortMode = 'selection';
let searchQuery = '';
const MAX_SIGNALS = 20;
function initWebSocket() {
ws = new WebSocket('ws://' + window.location.hostname + ':81');
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) {
try {
const data = JSON.parse(event.data);
} catch(e) {
console.error('Error parsing WebSocket data:', e);
}
};
}
function loadDBCFile(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
parseDBCContent(content);
document.getElementById('dbc-status').textContent = file.name;
saveDBCToLocalStorage(content, file.name);
};
reader.readAsText(file);
}
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);
}
}
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: {}, valueTables: {}};
allSignals = [];
const lines = content.split('\n');
let currentMessage = null;
// 먼저 VAL_ 정의를 파싱
for (let line of lines) {
line = line.trim();
if (line.startsWith('VAL_ ')) {
// VAL_ 형식: VAL_ <MessageID> <SignalName> <value> "<text>" ...;
const match = line.match(/VAL_\s+(\d+)\s+(\w+)\s+(.+);/);
if (match) {
const msgId = parseInt(match[1]);
const sigName = match[2];
const valuesStr = match[3];
// Extended CAN ID 처리
const normalizedMsgId = (msgId & 0x80000000) ? (msgId & 0x1FFFFFFF) : msgId;
const key = normalizedMsgId + '_' + sigName;
dbcData.valueTables[key] = {};
// 값-텍스트 쌍 파싱
const valueMatches = valuesStr.matchAll(/(\d+)\s+"([^"]+)"/g);
for (let vm of valueMatches) {
dbcData.valueTables[key][parseInt(vm[1])] = vm[2];
}
console.log('Parsed Value Table: ' + key, dbcData.valueTables[key]);
}
}
}
// 메시지와 시그널 파싱
for (let line of lines) {
line = line.trim();
if (line.startsWith('BO_ ')) {
const match = line.match(/BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)/);
if (match) {
let id = parseInt(match[1]);
const name = match[2];
const dlc = parseInt(match[3]); // CAN FD: DLC can be up to 64
if (id & 0x80000000) {
id = id & 0x1FFFFFFF;
}
currentMessage = {
id: id,
name: name,
dlc: dlc,
signals: []
};
dbcData.messages[id] = currentMessage;
const fdIndicator = dlc > 8 ? ' [FD]' : '';
console.log('Parsed Message: ID=' + id + ' (0x' + id.toString(16).toUpperCase() + ') Name=' + name + ' DLC=' + dlc + fdIndicator);
}
}
else if (line.startsWith('SG_ ') && currentMessage) {
const match = line.match(/SG_\s+(\w+)\s*:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,]+),([^)]+)\)\s*\[([^\]]+)\]\s*"([^"]*)"/);
if (match) {
const signalName = match[1];
const signal = {
name: signalName,
startBit: parseInt(match[2]), // CAN FD: can be 0-511
bitLength: parseInt(match[3]),
byteOrder: match[4] === '0' ? 'motorola' : 'intel',
signed: match[5] === '-',
factor: parseFloat(match[6]),
offset: parseFloat(match[7]),
minMax: match[8],
unit: match[9],
messageId: currentMessage.id,
messageName: currentMessage.name,
messageDlc: currentMessage.dlc
};
// Value Table 연결
const vtKey = currentMessage.id + '_' + signalName;
if (dbcData.valueTables[vtKey]) {
signal.valueTable = dbcData.valueTables[vtKey];
console.log(' Signal with value table: ' + signalName, signal.valueTable);
}
currentMessage.signals.push(signal);
allSignals.push(signal);
console.log(' Signal: ' + signal.name + ' [' + signal.startBit + '|' + signal.bitLength + '] Unit: ' + signal.unit);
}
}
}
filteredSignals = [...allSignals];
displaySignals();
// Count FD messages
let fdMsgCount = 0;
for (let id in dbcData.messages) {
if (dbcData.messages[id].dlc > 8) fdMsgCount++;
}
const fdInfo = fdMsgCount > 0 ? ' (' + fdMsgCount + ' FD messages)' : '';
showStatus('DBC loaded: ' + Object.keys(dbcData.messages).length + ' messages, ' + allSignals.length + ' signals' + fdInfo, 'success');
}
function filterSignals() {
searchQuery = document.getElementById('search-box').value.toLowerCase().trim();
if (searchQuery === '') {
filteredSignals = [...allSignals];
document.getElementById('search-info').style.display = 'none';
} else {
filteredSignals = allSignals.filter(signal => {
const nameMatch = signal.name.toLowerCase().includes(searchQuery);
const idDecMatch = signal.messageId.toString().includes(searchQuery);
const idHex = signal.messageId.toString(16).toLowerCase();
const idHexMatch = idHex.includes(searchQuery) ||
idHex.includes(searchQuery.replace('0x', ''));
const msgNameMatch = signal.messageName.toLowerCase().includes(searchQuery);
const unitMatch = signal.unit && signal.unit.toLowerCase().includes(searchQuery);
return nameMatch || idDecMatch || idHexMatch || msgNameMatch || unitMatch;
});
const searchInfo = document.getElementById('search-info');
searchInfo.textContent = 'Showing ' + filteredSignals.length + ' of ' + allSignals.length + ' signals';
searchInfo.style.display = 'block';
}
displaySignals();
}
function highlightText(text, query) {
if (!query) return text;
const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
return text.replace(regex, '<span class="highlight">$1</span>');
}
function setSortMode(mode) {
sortMode = mode;
document.querySelectorAll('.sort-btn').forEach(btn => btn.classList.remove('active'));
document.getElementById('sort-' + mode).classList.add('active');
displaySignals();
console.log('Sort mode changed to:', mode);
}
function sortSignals(signals) {
if (sortMode === 'name-asc') {
return signals.sort((a, b) => a.name.localeCompare(b.name));
} else if (sortMode === 'name-desc') {
return signals.sort((a, b) => b.name.localeCompare(a.name));
} else {
const selected = signals.filter(s => isSignalSelected(s));
const notSelected = signals.filter(s => !isSignalSelected(s));
return [...selected, ...notSelected];
}
}
function isSignalSelected(signal) {
return selectedSignals.some(s =>
s.messageId === signal.messageId && s.name === signal.name);
}
function displaySignals() {
const signalList = document.getElementById('signal-list');
signalList.innerHTML = '';
const sortedSignals = sortSignals([...filteredSignals]);
if (sortedSignals.length === 0) {
signalList.innerHTML = '<div class="no-results">' +
'<div class="no-results-icon">🔍</div>' +
'<div><strong>No signals found</strong></div>' +
'<div style="margin-top: 8px; color: #999;">Try a different search term</div>' +
'</div>';
return;
}
sortedSignals.forEach(signal => {
const item = document.createElement('div');
item.className = 'signal-item';
if (isSignalSelected(signal)) {
item.classList.add('selected');
}
item.onclick = () => toggleSignal(signal, item);
const canIdHex = '0x' + signal.messageId.toString(16).toUpperCase().padStart(3, '0');
const highlightedName = highlightText(signal.name, searchQuery);
const highlightedId = highlightText(canIdHex, searchQuery);
const highlightedMsgName = highlightText(signal.messageName, searchQuery);
const unitText = signal.unit ? highlightText(signal.unit, searchQuery) : 'no unit';
// Show FD indicator for signals in messages with DLC > 8
const fdBadge = signal.messageDlc > 8 ? ' <span style="background:#f7931e;color:white;padding:1px 4px;border-radius:3px;font-size:0.7em;">FD</span>' : '';
item.innerHTML =
'<div class="signal-name">' + highlightedName + fdBadge + '</div>' +
'<div class="signal-info">' +
'CAN ID: ' + highlightedId + ' (' + highlightedMsgName + ')<br>' +
'Bit: ' + signal.startBit + '|' + signal.bitLength + ' | ' + unitText +
'</div>';
signalList.appendChild(item);
});
document.getElementById('signal-section').style.display = 'block';
updateSelectionCount();
}
function updateSelectionCount() {
document.getElementById('selected-count').textContent = selectedSignals.length;
}
function toggleSignal(signal, element) {
const index = selectedSignals.findIndex(s =>
s.messageId === signal.messageId && s.name === signal.name);
if (index >= 0) {
selectedSignals.splice(index, 1);
element.classList.remove('selected');
} else {
if (selectedSignals.length >= MAX_SIGNALS) {
showStatus('Max ' + MAX_SIGNALS + ' signals!', 'error');
return;
}
selectedSignals.push(signal);
element.classList.add('selected');
}
updateSelectionCount();
saveSelectedSignals();
if (sortMode === 'selection') {
displaySignals();
}
}
function clearSelection() {
selectedSignals = [];
document.querySelectorAll('.signal-item').forEach(item => {
item.classList.remove('selected');
});
updateSelectionCount();
saveSelectedSignals();
if (sortMode === 'selection') {
displaySignals();
}
}
function saveSelectedSignals() {
try {
localStorage.setItem('selected_signals', JSON.stringify(selectedSignals));
localStorage.setItem('sort_mode', sortMode);
console.log('Saved', selectedSignals.length, 'signals with sort mode:', sortMode);
} catch(e) {
console.error('Failed to save selected signals:', e);
}
}
function loadSelectedSignals() {
try {
const saved = localStorage.getItem('selected_signals');
const savedSortMode = localStorage.getItem('sort_mode');
if (savedSortMode) {
sortMode = savedSortMode;
document.querySelectorAll('.sort-btn').forEach(btn => btn.classList.remove('active'));
document.getElementById('sort-' + sortMode).classList.add('active');
}
if (saved) {
const signals = JSON.parse(saved);
signals.forEach(savedSignal => {
let found = false;
for (let msgId in dbcData.messages) {
const msg = dbcData.messages[msgId];
const signal = msg.signals.find(s =>
s.messageId === savedSignal.messageId && s.name === savedSignal.name);
if (signal) {
selectedSignals.push(signal);
found = true;
break;
}
}
});
displaySignals();
if (selectedSignals.length > 0) {
showStatus('Restored ' + selectedSignals.length + ' selected signals', 'success');
}
}
} catch(e) {
console.error('Failed to load selected signals:', e);
}
}
function startGraphing() {
if (selectedSignals.length === 0) {
showStatus('Select at least one signal!', 'error');
return;
}
saveSelectedSignals();
const width = 1400;
const height = 900;
const left = (screen.width - width) / 2;
const top = (screen.height - height) / 2;
window.open(
'/graph-view',
'CAN_Graph_Viewer',
'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',resizable=yes,scrollbars=yes'
);
showStatus('Graph viewer opened in new window', 'success');
}
function stopGraphing() {
showStatus('Use the stop button in the graph viewer window', 'error');
}
function debugDBCInfo() {
console.log('=== DBC Debug Info ===');
console.log('Total Messages: ' + Object.keys(dbcData.messages).length);
console.log('Total Signals: ' + allSignals.length);
console.log('Total Value Tables: ' + Object.keys(dbcData.valueTables).length);
// Count FD messages
let fdMsgCount = 0;
for (let id in dbcData.messages) {
if (dbcData.messages[id].dlc > 8) fdMsgCount++;
}
console.log('CAN FD Messages (DLC > 8): ' + fdMsgCount);
console.log('\n=== Value Tables ===');
for (let key in dbcData.valueTables) {
console.log(key + ':', dbcData.valueTables[key]);
}
console.log('\n=== Messages ===');
Object.values(dbcData.messages).forEach(msg => {
const fdTag = msg.dlc > 8 ? ' [CAN FD]' : '';
console.log('\nMessage: ' + msg.name + fdTag);
console.log(' ID: ' + msg.id + ' (0x' + msg.id.toString(16).toUpperCase() + ')');
console.log(' DLC: ' + msg.dlc);
console.log(' Signals: ' + msg.signals.length);
msg.signals.forEach(sig => {
console.log(' - ' + sig.name + ': ' + sig.startBit + '|' + sig.bitLength + ' [' + sig.unit + ']');
if (sig.valueTable) {
console.log(' Value Table:', sig.valueTable);
}
});
});
showStatus('Debug info printed to console (F12)', 'success');
}
function showStatus(message, type) {
const status = document.getElementById('status');
status.textContent = message;
status.className = 'status ' + type;
status.style.display = 'block';
setTimeout(() => { status.style.display = 'none'; }, 5000);
}
const uploadArea = document.querySelector('.upload-area');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
uploadArea.addEventListener(eventName, e => {
e.preventDefault();
e.stopPropagation();
});
});
['dragenter', 'dragover'].forEach(eventName => {
uploadArea.addEventListener(eventName, () => {
uploadArea.style.borderColor = '#e85d04';
uploadArea.style.background = '#fff8f0';
});
});
['dragleave', 'drop'].forEach(eventName => {
uploadArea.addEventListener(eventName, () => {
uploadArea.style.borderColor = '#f7931e';
uploadArea.style.background = '';
});
});
uploadArea.addEventListener('drop', function(e) {
const file = e.dataTransfer.files[0];
if (file && file.name.endsWith('.dbc')) {
const reader = new FileReader();
reader.onload = function(ev) {
parseDBCContent(ev.target.result);
document.getElementById('dbc-status').textContent = file.name;
saveDBCToLocalStorage(ev.target.result, file.name);
};
reader.readAsText(file);
}
});
window.addEventListener('load', function() {
if (loadDBCFromLocalStorage()) {
setTimeout(() => loadSelectedSignals(), 100);
}
});
initWebSocket();
</script>
</body>
</html>
)rawliteral";
#endif

978
canfd_graph_viewer.h Normal file
View File

@@ -0,0 +1,978 @@
#ifndef CANFD_GRAPH_VIEWER_H
#define CANFD_GRAPH_VIEWER_H
const char canfd_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 FD Signal Graph Viewer</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #f7931e 0%, #e85d04 100%); padding: 10px;
color: white;
overflow-x: hidden;
}
.header {
background: linear-gradient(135deg, #f7931e, #e85d04);
padding: 15px;
text-align: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
}
.header h1 { font-size: 1.5em; }
.header p { font-size: 0.9em; opacity: 0.9; margin-top: 5px; }
/* ========== 통일된 네비게이션 ========== */
.nav {
background: #f8f9fa;
padding: 0;
border-bottom: 2px solid #e0e0e0;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.nav a {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 15px 20px;
text-decoration: none;
color: #666;
font-weight: 500;
font-size: 0.95em;
border-bottom: 3px solid transparent;
transition: all 0.3s;
white-space: nowrap;
min-width: 120px;
}
.nav a:hover {
background: #e9ecef;
color: #f7931e;
transform: translateY(-2px);
}
.nav a.active {
color: #e85d04;
border-bottom-color: #e85d04;
background: white;
font-weight: 600;
}
.controls {
background: #2a2a2a;
padding: 10px 15px;
display: flex;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
.control-group {
display: flex;
gap: 10px;
align-items: center;
}
.control-label {
font-size: 0.85em;
color: #aaa;
}
.btn {
padding: 8px 20px;
border: none;
border-radius: 5px;
font-size: 0.9em;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn-success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; }
.btn-danger { background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%); color: white; }
.btn-info { background: linear-gradient(135deg, #f7931e 0%, #e85d04 100%); color: white; }
.btn-warning { background: linear-gradient(135deg, #f2994a 0%, #f2c94c 100%); color: white; }
.btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
.btn.active {
box-shadow: inset 0 3px 5px rgba(0,0,0,0.3);
transform: translateY(0);
}
.graphs {
padding: 15px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
gap: 15px;
}
.graph-container {
background: #2a2a2a;
padding: 15px;
border-radius: 10px;
border: 2px solid #3a3a3a;
}
.graph-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
padding-bottom: 8px;
border-bottom: 2px solid #f7931e;
}
.graph-title {
font-size: 1em;
font-weight: 600;
color: #f7931e;
}
.graph-value {
font-size: 1.2em;
font-weight: 700;
color: #38ef7d;
font-family: 'Courier New', monospace;
}
canvas {
width: 100%;
height: 250px;
border: 1px solid #3a3a3a;
border-radius: 5px;
background: linear-gradient(135deg, #f7931e 0%, #e85d04 100%); padding: 10px;
}
.status {
position: fixed;
top: 10px;
right: 10px;
padding: 10px 15px;
border-radius: 5px;
background: #2a2a2a;
border: 2px solid #f7931e;
font-size: 0.9em;
z-index: 1000;
}
.status.disconnected {
border-color: #eb3349;
background: #3a2a2a;
}
/* ========== 반응형 디자인 ========== */
@media (max-width: 768px) {
body {
padding: 5px;
}
.container {
border-radius: 10px;
}
.header {
padding: 15px;
flex-direction: column;
text-align: center;
gap: 10px;
}
.header h1 {
font-size: 1.4em;
}
.nav {
padding: 5px;
}
.nav a {
padding: 12px 15px;
font-size: 0.85em;
}
.content {
padding: 15px;
}
.btn {
padding: 10px 20px;
font-size: 13px;
}
}
@media (min-width: 769px) and (max-width: 1024px) {
.header h1 {
font-size: 1.6em;
}
.nav a {
padding: 13px 18px;
font-size: 0.9em;
}
.content {
padding: 25px;
}
}
@media (min-width: 1025px) {
.content {
padding: 30px;
}
}
</style>
</head>
<body>
<div class="header">
<h1>🚀 CAN FD Real-time Signal Graphs</h1>
<p>Viewing <span id="graph-count">0</span> signals (64-byte support)</p>
</div>
<div class="nav">
<a href="/">📊 Dashboard</a>
<a href="/settings"> Settings</a>
<a href="/graph">📈 Graph</a>
<a href="/graph-view" class="active">📊 Graph View</a>
</div>
<div class="controls">
<div class="control-group">
<button class="btn btn-success" onclick="startGraphing()">Start</button>
<button class="btn btn-danger" onclick="stopGraphing()">Stop</button>
<button class="btn btn-danger" onclick="window.close()">Close</button>
</div>
<div class="control-group">
<span class="control-label">X-Axis 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-Based</button>
</div>
<div class="control-group">
<span class="control-label">X-Axis Range:</span>
<button class="btn btn-warning active" id="btn-range-10s" onclick="setRangeMode('10s')">10s Window</button>
<button class="btn btn-warning" id="btn-range-all" onclick="setRangeMode('all')">All Time</button>
</div>
<div class="control-group">
<span class="control-label">Sort by:</span>
<button class="btn btn-info active" id="btn-sort-selection" onclick="setSortMode('selection')">Selection Order</button>
<button class="btn btn-info" id="btn-sort-name-asc" onclick="setSortMode('name-asc')">Name (AZ)</button>
<button class="btn btn-info" id="btn-sort-name-desc" onclick="setSortMode('name-desc')">Name (ZA)</button>
</div>
<div class="control-group">
<button class="btn btn-success" onclick="downloadCSV()" style="background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);">
📥 Download CSV
</button>
<button class="btn btn-danger" onclick="clearData()" style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);">
🗑 Clear Data
</button>
</div>
</div>
<div class="status" id="status">Connecting...</div>
<div style="padding: 10px 15px; background: #2a2a2a; color: #aaa; font-size: 0.85em; display: flex; justify-content: space-between; align-items: center;">
<span>Data Points: <strong id="data-point-count" style="color: #f7931e;">0</strong></span>
<span>Recording Time: <strong id="recording-time" style="color: #f7931e;">0s</strong></span>
<span>Messages Received: <strong id="msg-received" style="color: #f7931e;">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 = 60;
let scaleMode = 'index';
let rangeMode = '10s';
let totalMsgReceived = 0;
let lastCanCounts = {}; // ★ 각 CAN ID별 마지막 count 저장
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();
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, 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();
}
this.draw();
}
getValueText(value) {
if (this.signal.valueTable && this.signal.valueTable[value] !== undefined) {
return this.signal.valueTable[value];
}
return value.toFixed(2);
}
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);
let displayData = [];
let displayTimes = [];
let displayLabels = [];
if (rangeMode === '10s') {
const currentTime = this.times[this.times.length - 1];
for (let i = 0; i < this.times.length; i++) {
if (currentTime - this.times[i] <= 10) {
displayData.push(this.data[i]);
displayTimes.push(this.times[i]);
displayLabels.push(this.labels[i]);
}
}
} else {
displayData = [...this.data];
displayTimes = [...this.times];
displayLabels = [...this.labels];
}
if (displayData.length === 0) return;
const minValue = Math.min(...displayData);
const maxValue = Math.max(...displayData);
const range = maxValue - minValue || 1;
let minTime, maxTime, timeRange;
if (scaleMode === 'time') {
minTime = displayTimes[0];
maxTime = displayTimes[displayTimes.length - 1];
timeRange = maxTime - minTime || 1;
}
ctx.strokeStyle = '#444';
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();
ctx.fillStyle = '#aaa';
ctx.font = '11px Arial';
ctx.textAlign = 'right';
if (this.signal.valueTable) {
const uniqueValues = [...new Set(displayData)].sort((a, b) => a - b);
if (uniqueValues.length <= 5) {
uniqueValues.forEach((val, idx) => {
const y = this.height - padding - ((val - minValue) / range) * graphHeight;
const text = this.getValueText(val);
ctx.fillText(text, padding - 5, y + 5);
});
} else {
ctx.fillText(this.getValueText(maxValue), padding - 5, padding + 5);
ctx.fillText(this.getValueText(minValue), padding - 5, this.height - padding);
}
} else {
ctx.fillText(maxValue.toFixed(2), padding - 5, padding + 5);
ctx.fillText(minValue.toFixed(2), padding - 5, this.height - padding);
}
ctx.textAlign = 'center';
ctx.fillStyle = '#aaa';
ctx.font = '10px Arial';
if (displayLabels.length > 0) {
ctx.fillText(displayLabels[0] + 's', padding, this.height - padding + 15);
if (displayLabels.length > 1) {
ctx.fillText(displayLabels[displayLabels.length - 1] + 's', this.width - padding, this.height - padding + 15);
}
}
ctx.beginPath();
ctx.strokeStyle = this.colors.line;
ctx.lineWidth = 2;
for (let i = 0; i < displayData.length; i++) {
let x;
if (scaleMode === 'time') {
x = padding + ((displayTimes[i] - minTime) / timeRange) * graphWidth;
} else {
x = padding + (i / (displayData.length - 1 || 1)) * graphWidth;
}
const y = this.height - padding - ((displayData[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 < displayData.length; i++) {
let x;
if (scaleMode === 'time') {
x = padding + ((displayTimes[i] - minTime) / timeRange) * graphWidth;
} else {
x = padding + (i / (displayData.length - 1 || 1)) * graphWidth;
}
const y = this.height - padding - ((displayData[i] - minValue) / range) * graphHeight;
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI * 2);
ctx.fill();
}
}
}
function loadData() {
try {
const signalsJson = localStorage.getItem('selected_signals');
const dbcContent = localStorage.getItem('dbc_content');
const savedSortMode = localStorage.getItem('sort_mode');
if (!signalsJson || !dbcContent) {
console.error('No saved signals or DBC found in localStorage');
document.getElementById('status').textContent = 'No signals selected. Go to Graph page first.';
document.getElementById('status').classList.add('disconnected');
return false;
}
if (savedSortMode) {
sortMode = savedSortMode;
document.querySelectorAll('.control-group .btn-info').forEach(btn => btn.classList.remove('active'));
document.getElementById('btn-sort-' + sortMode).classList.add('active');
}
parseDBCContent(dbcContent);
const savedSignals = JSON.parse(signalsJson);
selectedSignals = [];
savedSignals.forEach(savedSignal => {
for (let msgId in dbcData.messages) {
const msg = dbcData.messages[msgId];
const signal = msg.signals.find(s =>
s.messageId === savedSignal.messageId && s.name === savedSignal.name);
if (signal) {
selectedSignals.push(signal);
break;
}
}
});
console.log('Loaded', selectedSignals.length, 'signals from localStorage');
return selectedSignals.length > 0;
} catch(e) {
console.error('Error loading data:', e);
return false;
}
}
function parseDBCContent(content) {
dbcData = {messages: {}, valueTables: {}};
const lines = content.split('\n');
let currentMessage = null;
for (let line of lines) {
line = line.trim();
if (line.startsWith('VAL_ ')) {
const match = line.match(/VAL_\s+(\d+)\s+(\w+)\s+(.+);/);
if (match) {
const msgId = parseInt(match[1]);
const sigName = match[2];
const valuesStr = match[3];
const normalizedMsgId = (msgId & 0x80000000) ? (msgId & 0x1FFFFFFF) : msgId;
const key = normalizedMsgId + '_' + sigName;
dbcData.valueTables[key] = {};
const valueMatches = valuesStr.matchAll(/(\d+)\s+"([^"]+)"/g);
for (let vm of valueMatches) {
dbcData.valueTables[key][parseInt(vm[1])] = vm[2];
}
}
}
}
for (let line of lines) {
line = line.trim();
if (line.startsWith('BO_ ')) {
const match = line.match(/BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)/);
if (match) {
let id = parseInt(match[1]);
const name = match[2];
const dlc = parseInt(match[3]); // CAN FD: DLC can be up to 64
if (id & 0x80000000) {
id = id & 0x1FFFFFFF;
}
currentMessage = {
id: id,
name: name,
dlc: dlc,
signals: []
};
dbcData.messages[id] = currentMessage;
}
}
else if (line.startsWith('SG_ ') && currentMessage) {
const match = line.match(/SG_\s+(\w+)\s*:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,]+),([^)]+)\)\s*\[([^\]]+)\]\s*"([^"]*)"/);
if (match) {
const signalName = match[1];
const signal = {
name: signalName,
startBit: parseInt(match[2]), // CAN FD: can be 0-511
bitLength: parseInt(match[3]),
byteOrder: match[4] === '0' ? 'motorola' : 'intel',
signed: match[5] === '-',
factor: parseFloat(match[6]),
offset: parseFloat(match[7]),
minMax: match[8],
unit: match[9],
messageId: currentMessage.id,
messageName: currentMessage.name,
messageDlc: currentMessage.dlc
};
const vtKey = currentMessage.id + '_' + signalName;
if (dbcData.valueTables[vtKey]) {
signal.valueTable = dbcData.valueTables[vtKey];
}
currentMessage.signals.push(signal);
}
}
}
}
function sortSignalsForDisplay() {
let sorted = [...selectedSignals];
if (sortMode === 'name-asc') {
sorted.sort((a, b) => a.name.localeCompare(b.name));
} else if (sortMode === 'name-desc') {
sorted.sort((a, b) => b.name.localeCompare(a.name));
}
return sorted;
}
function createGraphs() {
const container = document.getElementById('graphs');
container.innerHTML = '';
charts = {};
const sortedSignals = sortSignalsForDisplay();
sortedSignals.forEach((signal, index) => {
const div = document.createElement('div');
div.className = 'graph-container';
const canIdHex = '0x' + signal.messageId.toString(16).toUpperCase().padStart(3, '0');
const fdBadge = signal.messageDlc > 8 ? ' <span style="background:#f7931e;color:white;padding:1px 4px;border-radius:3px;font-size:0.7em;">FD</span>' : '';
div.innerHTML = `
<div class="graph-header">
<span class="graph-title">${signal.name}${fdBadge} (${canIdHex})</span>
<span class="graph-value" id="value-${index}">--</span>
</div>
<canvas id="chart-${index}"></canvas>
`;
container.appendChild(div);
const canvas = document.getElementById('chart-' + index);
charts[index] = new SimpleChart(canvas, signal, index);
});
document.getElementById('graph-count').textContent = selectedSignals.length;
}
function initWebSocket() {
ws = new WebSocket('ws://' + window.location.hostname + ':81');
ws.onopen = function() {
console.log('WebSocket connected');
document.getElementById('status').textContent = 'Connected';
document.getElementById('status').classList.remove('disconnected');
};
ws.onclose = function() {
console.log('WebSocket disconnected');
document.getElementById('status').textContent = 'Disconnected';
document.getElementById('status').classList.add('disconnected');
setTimeout(initWebSocket, 3000);
};
ws.onmessage = function(event) {
if (!graphing) return;
try {
const data = JSON.parse(event.data);
if (data.messages && Array.isArray(data.messages)) {
processMessages(data.messages);
}
} catch(e) {
console.error('Error parsing WebSocket message:', e);
}
};
}
function startGraphing() {
graphing = true;
startTime = Date.now();
console.log('Started graphing at', new Date(startTime).toISOString());
}
function stopGraphing() {
graphing = false;
console.log('Stopped graphing');
}
function setScaleMode(mode) {
scaleMode = mode;
document.getElementById('btn-index-mode').classList.remove('active');
document.getElementById('btn-time-mode').classList.remove('active');
document.getElementById('btn-' + mode + '-mode').classList.add('active');
Object.values(charts).forEach(chart => chart.draw());
console.log('Scale mode changed to:', mode);
}
function setRangeMode(mode) {
rangeMode = mode;
document.getElementById('btn-range-10s').classList.remove('active');
document.getElementById('btn-range-all').classList.remove('active');
document.getElementById('btn-range-' + mode).classList.add('active');
Object.values(charts).forEach(chart => chart.draw());
console.log('Range mode changed to:', mode);
}
function setSortMode(mode) {
sortMode = mode;
document.getElementById('btn-sort-selection').classList.remove('active');
document.getElementById('btn-sort-name-asc').classList.remove('active');
document.getElementById('btn-sort-name-desc').classList.remove('active');
document.getElementById('btn-sort-' + mode).classList.add('active');
const oldCharts = { ...charts };
createGraphs();
console.log('Sort mode changed to:', mode);
}
function processMessages(messages) {
const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(2);
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 문자열에서 바이트 배열로 변환 후 디코딩 (CAN FD 64바이트 지원)
function decodeSignalFromHex(signal, hexData) {
const bytes = [];
const cleanHex = hexData.toUpperCase();
// CAN FD: 64 bytes = 128 hex characters
for (let i = 0; i < cleanHex.length && i < 128; i += 2) {
bytes.push(parseInt(cleanHex.substring(i, i + 2), 16));
}
// CAN FD: pad to 64 bytes
while (bytes.length < 64) bytes.push(0);
return decodeSignalFromBytes(signal, bytes);
}
// ★ CAN FD 64바이트 지원 디코딩 함수
function decodeSignal(signal, hexData) {
const bytes = [];
if (typeof hexData === 'string') {
const cleanHex = hexData.replace(/\s/g, '').toUpperCase();
// CAN FD: 64 bytes = 128 hex characters
for (let i = 0; i < cleanHex.length && i < 128; i += 2) {
bytes.push(parseInt(cleanHex.substring(i, i + 2), 16));
}
} else if (Array.isArray(hexData)) {
bytes.push(...hexData);
}
// CAN FD: pad to 64 bytes
while (bytes.length < 64) bytes.push(0);
return decodeSignalFromBytes(signal, bytes);
}
function decodeSignalFromBytes(signal, bytes) {
let rawValue = 0;
if (signal.byteOrder === 'intel') {
// Intel (Little Endian) byte order
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 {
// Motorola (Big Endian) byte order
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));
}
}
}
// Handle signed values
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', 'canfd_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 = {}; // ★ count 기록도 초기화
startTime = Date.now();
totalMsgReceived = 0;
updateStatistics();
console.log('All data cleared');
}
if (loadData()) {
createGraphs();
initWebSocket();
startGraphing();
}
</script>
</body>
</html>
)rawliteral";
#endif

581
canfd_index.h Normal file
View File

@@ -0,0 +1,581 @@
#ifndef CANFD_INDEX_H
#define CANFD_INDEX_H
const char canfd_index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ESP32-S3 CAN FD Logger</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 10px;
}
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
border-radius: 15px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
text-align: center;
}
.header h1 { font-size: 28px; margin-bottom: 5px; }
.header p { opacity: 0.9; font-size: 14px; }
/* Navigation */
.nav {
background: #f8f9fa;
padding: 0;
border-bottom: 2px solid #e0e0e0;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.nav a {
padding: 15px 20px;
text-decoration: none;
color: #666;
font-weight: 500;
font-size: 14px;
border-bottom: 3px solid transparent;
transition: all 0.3s;
}
.nav a:hover {
background: #e9ecef;
color: #667eea;
}
.nav a.active {
color: #764ba2;
border-bottom-color: #764ba2;
background: white;
font-weight: 600;
}
.content { padding: 20px; }
/* Status Cards */
.status-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-bottom: 20px;
}
.status-card {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.status-card h3 {
color: #666;
font-size: 13px;
margin-bottom: 10px;
text-transform: uppercase;
}
.status-card .value {
color: #333;
font-size: 24px;
font-weight: 600;
}
.status-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
}
.status-ok { background: #10b981; color: white; }
.status-error { background: #ef4444; color: white; }
.status-warn { background: #f59e0b; color: white; }
/* Controls */
.controls {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
}
.controls h2 {
color: #333;
font-size: 18px;
margin-bottom: 15px;
}
.btn-group {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
}
.btn {
padding: 12px 20px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn-start { background: #10b981; color: white; }
.btn-start:hover { background: #059669; }
.btn-stop { background: #ef4444; color: white; }
.btn-stop:hover { background: #dc2626; }
.btn-refresh { background: #667eea; color: white; }
.btn-refresh:hover { background: #5568d3; }
/* Settings */
.settings-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
margin-bottom: 20px;
}
.setting-group {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
}
.setting-label {
color: #666;
font-size: 13px;
font-weight: 600;
margin-bottom: 8px;
display: block;
}
select, input {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 14px;
}
/* File List */
.file-section {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-top: 20px;
}
.file-section h2 {
color: #333;
font-size: 18px;
margin-bottom: 15px;
}
.file-list {
max-height: 400px;
overflow-y: auto;
}
.file-item {
background: white;
padding: 12px 15px;
margin-bottom: 8px;
border-radius: 8px;
display: flex;
align-items: center;
gap: 10px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.file-item:hover {
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.file-checkbox {
width: 18px;
height: 18px;
}
.file-info {
flex: 1;
}
.file-name {
font-weight: 600;
color: #333;
font-size: 14px;
}
.file-size {
color: #999;
font-size: 12px;
margin-left: 10px;
}
.file-actions {
display: flex;
gap: 5px;
}
.file-btn {
padding: 6px 12px;
border: none;
border-radius: 5px;
font-size: 12px;
cursor: pointer;
transition: all 0.3s;
}
.btn-download { background: #10b981; color: white; }
.btn-download:hover { background: #059669; }
.btn-delete { background: #ef4444; color: white; }
.btn-delete:hover { background: #dc2626; }
/* Real-time Monitor */
.monitor {
background: #1a1a1a;
color: #00ff00;
padding: 15px;
border-radius: 8px;
font-family: 'Courier New', monospace;
font-size: 12px;
max-height: 300px;
overflow-y: auto;
margin-top: 20px;
}
.monitor-line {
margin-bottom: 2px;
white-space: nowrap;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🚗 ESP32-S3 CAN FD Logger</h1>
<p>MCP2517FD High-Speed Data Logger with Web Interface</p>
</div>
<div class="nav">
<a href="/" class="active">📊 Dashboard</a>
<a href="/settings"> Settings</a>
</div>
<div class="content">
<!-- System Status -->
<div class="status-grid">
<div class="status-card">
<h3>CAN Controller</h3>
<div class="value">
<span class="status-badge" id="canStatus">Loading...</span>
</div>
</div>
<div class="status-card">
<h3>SD Card</h3>
<div class="value">
<span class="status-badge" id="sdStatus">Loading...</span>
</div>
</div>
<div class="status-card">
<h3>Total Frames</h3>
<div class="value" id="canFrames">0</div>
</div>
<div class="status-card">
<h3>Queue Usage</h3>
<div class="value" id="queueUsage">0 / 10000</div>
</div>
<div class="status-card">
<h3>Errors</h3>
<div class="value" id="canErrors">0</div>
</div>
<div class="status-card">
<h3>Free PSRAM</h3>
<div class="value" id="psram">- KB</div>
</div>
</div>
<!-- CAN Settings -->
<div class="settings-grid">
<div class="setting-group">
<label class="setting-label">CAN Mode</label>
<select id="canMode">
<option value="fd">CAN FD Mode</option>
<option value="classic">Classic CAN Mode</option>
</select>
</div>
<div class="setting-group">
<label class="setting-label">Bit Rate</label>
<select id="bitRate">
<option value="125000">125 kbps</option>
<option value="250000">250 kbps</option>
<option value="500000" selected>500 kbps</option>
<option value="1000000">1 Mbps</option>
</select>
</div>
<div class="setting-group" id="dataRateGroup">
<label class="setting-label">Data Rate (CAN FD)</label>
<select id="dataRate">
<option value="1">x1</option>
<option value="2">x2</option>
<option value="4" selected>x4 (2 Mbps)</option>
<option value="8">x8</option>
</select>
</div>
<div class="setting-group">
<label class="setting-label">Controller Mode</label>
<select id="controllerMode">
<option value="0" selected>Normal</option>
<option value="1">Listen Only</option>
<option value="2">Loopback</option>
</select>
</div>
</div>
<!-- Logging Controls -->
<div class="controls">
<h2>🎬 Logging Control</h2>
<div class="btn-group">
<button class="btn btn-start" onclick="startLogging()"> Start Logging</button>
<button class="btn btn-stop" onclick="stopLogging()"> Stop Logging</button>
<button class="btn btn-refresh" onclick="applySettings()">💾 Apply Settings</button>
<button class="btn btn-refresh" onclick="loadFileList()">🔄 Refresh Files</button>
</div>
</div>
<!-- File List -->
<div class="file-section">
<h2>📁 Log Files on SD Card</h2>
<div style="margin-bottom: 10px;">
<button class="btn btn-start" onclick="downloadSelected()" style="padding: 8px 16px;"> Download Selected</button>
<button class="btn btn-delete" onclick="deleteSelected()" style="padding: 8px 16px;">🗑 Delete Selected</button>
</div>
<div class="file-list" id="fileList">
<p style="text-align: center; color: #999; padding: 20px;">Loading files...</p>
</div>
</div>
<!-- Real-time Monitor -->
<div class="controls">
<h2>📺 Real-time CAN Monitor</h2>
<div class="monitor" id="monitor">
<div class="monitor-line">Waiting for CAN messages...</div>
</div>
</div>
</div>
</div>
<script>
let ws;
let monitorLines = [];
const MAX_MONITOR_LINES = 50;
// WebSocket connection
function initWebSocket() {
ws = new WebSocket('ws://' + window.location.hostname + ':81');
ws.onopen = function() {
console.log('WebSocket connected');
updateStatus();
loadFileList();
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.type === 'status') {
updateStatusDisplay(data);
} else if (data.type === 'canMessage') {
addMonitorLine(data);
} else if (data.type === 'files') {
displayFiles(data.files);
}
};
ws.onclose = function() {
console.log('WebSocket disconnected');
setTimeout(initWebSocket, 3000);
};
}
function updateStatus() {
fetch('/status')
.then(r => r.json())
.then(data => updateStatusDisplay(data))
.catch(err => console.error('Status update failed:', err));
}
function updateStatusDisplay(data) {
// CAN Status
const canStatus = document.getElementById('canStatus');
if (data.canReady) {
canStatus.className = 'status-badge status-ok';
canStatus.textContent = 'Ready';
} else {
canStatus.className = 'status-badge status-error';
canStatus.textContent = 'Offline';
}
// SD Status
const sdStatus = document.getElementById('sdStatus');
if (data.sdReady) {
sdStatus.className = 'status-badge status-ok';
sdStatus.textContent = 'Ready';
} else {
sdStatus.className = 'status-badge status-error';
sdStatus.textContent = 'Error';
}
// Statistics
document.getElementById('canFrames').textContent = data.canFrames.toLocaleString();
document.getElementById('queueUsage').textContent = data.queueUsage + ' / 10000';
document.getElementById('canErrors').textContent = data.canErrors;
document.getElementById('psram').textContent = data.freePsram + ' KB';
}
function addMonitorLine(msg) {
const line = `[${msg.timestamp}] ID: 0x${msg.id} DLC: ${msg.len} ${msg.fd ? 'FD' : 'CAN'} ${msg.brs ? 'BRS' : ''} Data: ${msg.data}`;
monitorLines.push(line);
if (monitorLines.length > MAX_MONITOR_LINES) {
monitorLines.shift();
}
const monitor = document.getElementById('monitor');
monitor.innerHTML = monitorLines.map(l => `<div class="monitor-line">${l}</div>`).join('');
monitor.scrollTop = monitor.scrollHeight;
}
function startLogging() {
fetch('/logging/start', {method: 'POST'})
.then(r => r.json())
.then(data => {
alert(data.message);
updateStatus();
loadFileList();
});
}
function stopLogging() {
fetch('/logging/stop', {method: 'POST'})
.then(r => r.json())
.then(data => {
alert(data.message);
updateStatus();
loadFileList();
});
}
function applySettings() {
const settings = {
mode: document.getElementById('canMode').value,
bitRate: parseInt(document.getElementById('bitRate').value),
dataRate: parseInt(document.getElementById('dataRate').value),
controllerMode: parseInt(document.getElementById('controllerMode').value)
};
fetch('/settings/apply', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(settings)
})
.then(r => r.json())
.then(data => {
alert(data.message + '\n\nPlease restart ESP32 to apply changes.');
});
}
function loadFileList() {
fetch('/files/list')
.then(r => r.json())
.then(data => displayFiles(data.files))
.catch(err => console.error('File list failed:', err));
}
function displayFiles(files) {
const fileList = document.getElementById('fileList');
if (!files || files.length === 0) {
fileList.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">No files found</p>';
return;
}
fileList.innerHTML = files.map(file => `
<div class="file-item">
<input type="checkbox" class="file-checkbox" value="${file.name}">
<div class="file-info">
<span class="file-name">${file.name}</span>
<span class="file-size">${formatBytes(file.size)}</span>
</div>
<div class="file-actions">
<button class="file-btn btn-download" onclick="downloadFile('${file.name}')">Download</button>
<button class="file-btn btn-delete" onclick="deleteFile('${file.name}')">Delete</button>
</div>
</div>
`).join('');
}
function downloadFile(filename) {
window.location.href = '/download?file=' + encodeURIComponent(filename);
}
function deleteFile(filename) {
if (!confirm(`Delete "${filename}"?\n\nThis cannot be undone.`)) return;
fetch('/files/delete', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({filename: filename})
})
.then(r => r.json())
.then(data => {
alert(data.message);
loadFileList();
});
}
function downloadSelected() {
const selected = Array.from(document.querySelectorAll('.file-checkbox:checked'))
.map(cb => cb.value);
if (selected.length === 0) {
alert('Please select files to download');
return;
}
selected.forEach(filename => {
setTimeout(() => downloadFile(filename), 100);
});
}
function deleteSelected() {
const selected = Array.from(document.querySelectorAll('.file-checkbox:checked'))
.map(cb => cb.value);
if (selected.length === 0) {
alert('Please select files to delete');
return;
}
if (!confirm(`Delete ${selected.length} file(s)?\n\nThis cannot be undone.`)) return;
selected.forEach(filename => deleteFile(filename));
}
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// CAN Mode change handler
document.getElementById('canMode').addEventListener('change', function() {
const dataRateGroup = document.getElementById('dataRateGroup');
if (this.value === 'classic') {
dataRateGroup.style.display = 'none';
} else {
dataRateGroup.style.display = 'block';
}
});
// Initialize
initWebSocket();
setInterval(updateStatus, 2000);
</script>
</body>
</html>
)rawliteral";
#endif

550
transmit.h Normal file
View File

@@ -0,0 +1,550 @@
#ifndef CANFD_SETTINGS_H
#define CANFD_SETTINGS_H
const char canfd_settings_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings - ESP32-S3 CAN FD Logger</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 10px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 15px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
text-align: center;
}
.header h1 { font-size: 28px; margin-bottom: 5px; }
.header p { opacity: 0.9; font-size: 14px; }
/* Navigation */
.nav {
background: #f8f9fa;
padding: 0;
border-bottom: 2px solid #e0e0e0;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.nav a {
padding: 15px 20px;
text-decoration: none;
color: #666;
font-weight: 500;
font-size: 14px;
border-bottom: 3px solid transparent;
transition: all 0.3s;
}
.nav a:hover {
background: #e9ecef;
color: #667eea;
}
.nav a.active {
color: #764ba2;
border-bottom-color: #764ba2;
background: white;
font-weight: 600;
}
.content { padding: 30px; }
.settings-section {
background: #f8f9fa;
padding: 25px;
border-radius: 10px;
margin-bottom: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.section-title {
color: #333;
font-size: 20px;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 3px solid #667eea;
display: flex;
align-items: center;
gap: 10px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-weight: 600;
color: #333;
margin-bottom: 8px;
font-size: 14px;
}
.help-text {
font-size: 12px;
color: #666;
margin-top: 5px;
line-height: 1.4;
}
input[type="text"],
input[type="password"],
select {
width: 100%;
padding: 12px 15px;
border: 2px solid #e1e8ed;
border-radius: 8px;
font-size: 14px;
transition: all 0.3s;
background: white;
}
input:focus, select:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
input[type="checkbox"] {
width: 20px;
height: 20px;
cursor: pointer;
margin-right: 10px;
}
.checkbox-group {
display: flex;
align-items: center;
margin-bottom: 15px;
}
.checkbox-group label {
margin-bottom: 0;
cursor: pointer;
}
.sta-settings {
background: #f0f4f8;
padding: 20px;
border-radius: 8px;
margin-top: 15px;
border-left: 4px solid #667eea;
}
.sta-settings.disabled {
opacity: 0.5;
pointer-events: none;
}
.button-group {
display: flex;
gap: 15px;
margin-top: 30px;
flex-wrap: wrap;
}
button {
flex: 1;
min-width: 150px;
padding: 14px 28px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
transition: all 0.3s;
text-transform: uppercase;
}
.btn-save {
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
color: white;
box-shadow: 0 4px 15px rgba(17, 153, 142, 0.3);
}
.btn-save:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(17, 153, 142, 0.4);
}
.btn-cancel {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}
.btn-cancel:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}
.alert {
padding: 15px 20px;
border-radius: 8px;
margin-bottom: 20px;
display: none;
align-items: center;
gap: 12px;
}
.alert.show {
display: flex;
}
.alert-success {
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
color: white;
}
.alert-info {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.alert-icon {
font-size: 20px;
}
.alert-text {
flex: 1;
font-weight: 600;
}
.info-box {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
border-left: 4px solid #667eea;
padding: 15px 20px;
border-radius: 8px;
margin-top: 15px;
}
.info-box-title {
font-weight: 700;
color: #333;
margin-bottom: 8px;
}
.info-box-text {
color: #555;
font-size: 13px;
line-height: 1.6;
}
.sta-status {
margin-top: 15px;
padding: 12px;
background: #e8f5e9;
border-radius: 6px;
color: #2e7d32;
font-weight: 600;
display: none;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1> Settings</h1>
<p>Configure WiFi and CAN Settings</p>
</div>
<div class="nav">
<a href="/">📊 Dashboard</a>
<a href="/settings" class="active"> Settings</a>
<a href="/graph">📈 Graph</a>
</div>
<div class="content">
<div id="alert-success" class="alert alert-success">
<span class="alert-icon"></span>
<span class="alert-text">Settings saved successfully!</span>
</div>
<div id="alert-loading" class="alert alert-info">
<span class="alert-icon"></span>
<span class="alert-text">Loading settings...</span>
</div>
<!-- WiFi Settings -->
<div class="settings-section">
<div class="section-title">
<span>📶</span>
<span>WiFi Configuration</span>
</div>
<h3 style="color: #333; font-size: 16px; margin-bottom: 15px;">AP Mode (Access Point)</h3>
<div class="form-group">
<label for="wifi-ssid">AP SSID ( )</label>
<input type="text" id="wifi-ssid" placeholder="Byun_CANFD_Logger" maxlength="31">
<div class="help-text">ESP32가 WiFi ( 31)</div>
</div>
<div class="form-group">
<label for="wifi-password">AP Password ()</label>
<input type="password" id="wifi-password" placeholder="최소 8자 이상" minlength="8" maxlength="63">
<div class="help-text">WiFi (8-63)</div>
</div>
<hr style="margin: 25px 0; border: none; border-top: 1px solid #ddd;">
<h3 style="color: #333; font-size: 16px; margin-bottom: 15px;">APSTA Mode (AP + Station)</h3>
<div class="checkbox-group">
<input type="checkbox" id="sta-enable" onchange="toggleSTASettings()">
<label for="sta-enable">Station ( WiFi에 )</label>
</div>
<div class="help-text" style="margin-left: 30px; margin-bottom: 15px;">
AP와 Station을
</div>
<div id="sta-settings" class="sta-settings disabled">
<div class="form-group">
<label for="sta-ssid"> WiFi SSID</label>
<input type="text" id="sta-ssid" placeholder="공유기 이름 입력" maxlength="31">
<div class="help-text"> WiFi </div>
</div>
<div class="form-group">
<label for="sta-password"> WiFi Password</label>
<input type="password" id="sta-password" placeholder="공유기 비밀번호 입력" maxlength="63">
<div class="help-text"> WiFi </div>
</div>
<div id="sta-status" class="sta-status">
WiFi : <span id="sta-ip"></span>
</div>
</div>
</div>
<!-- CAN Settings -->
<div class="settings-section">
<div class="section-title">
<span>🚗</span>
<span>CAN Configuration</span>
</div>
<div class="form-group">
<label for="can-mode">CAN Mode</label>
<select id="can-mode" onchange="toggleDataRate()">
<option value="fd">CAN FD Mode</option>
<option value="classic">Classic CAN Mode</option>
</select>
<div class="help-text">CAN FD: 64, Classic CAN: 8</div>
</div>
<div class="form-group">
<label for="bit-rate">Arbitration Bit Rate</label>
<select id="bit-rate">
<option value="125000">125 kbps</option>
<option value="250000">250 kbps</option>
<option value="500000" selected>500 kbps</option>
<option value="1000000">1 Mbps</option>
</select>
<div class="help-text">CAN </div>
</div>
<div class="form-group" id="data-rate-group">
<label for="data-rate">Data Rate Factor (CAN FD만)</label>
<select id="data-rate">
<option value="1">x1</option>
<option value="2">x2</option>
<option value="4" selected>x4 ()</option>
<option value="8">x8</option>
</select>
<div class="help-text">CAN FD </div>
</div>
<div class="form-group">
<label for="controller-mode">Controller Mode</label>
<select id="controller-mode">
<option value="0" selected>Normal</option>
<option value="1">Listen Only</option>
<option value="2">Loopback</option>
</select>
<div class="help-text">Normal: , Listen Only: </div>
</div>
</div>
<div class="button-group">
<button class="btn-save" onclick="saveSettings()">💾 Save Settings</button>
<button class="btn-cancel" onclick="location.href='/'"> Back to Dashboard</button>
</div>
<div class="info-box">
<div class="info-box-title">
</div>
<div class="info-box-text">
WiFi , <strong>ESP32를 </strong> SSID/ .<br>
<strong>APSTA :</strong> Station ESP32가 AP와 Station을 .<br>
Station WiFi에 .<br>
Station AP .<br>
CAN <strong>ESP32 </strong> .<br>
ESP32의 <strong>RST </strong> .
</div>
</div>
</div>
</div>
<script>
function loadSettings() {
fetch('/settings/get')
.then(r => r.json())
.then(data => {
// WiFi settings
document.getElementById('wifi-ssid').value = data.wifiSSID || 'Byun_CANFD_Logger';
document.getElementById('wifi-password').value = data.wifiPassword || '';
// STA settings
document.getElementById('sta-enable').checked = data.staEnable || false;
document.getElementById('sta-ssid').value = data.staSSID || '';
document.getElementById('sta-password').value = data.staPassword || '';
// CAN settings
document.getElementById('can-mode').value = data.canMode || 'fd';
document.getElementById('bit-rate').value = data.bitRate || 500000;
document.getElementById('data-rate').value = data.dataRate || 4;
document.getElementById('controller-mode').value = data.controllerMode || 0;
// Update UI
toggleSTASettings();
toggleDataRate();
// STA status
if (data.staConnected && data.staIP && data.staIP !== '0.0.0.0') {
document.getElementById('sta-ip').textContent = data.staIP;
document.getElementById('sta-status').style.display = 'block';
} else {
document.getElementById('sta-status').style.display = 'none';
}
hideAlert('alert-loading');
})
.catch(err => {
console.error('Failed to load settings:', err);
hideAlert('alert-loading');
});
}
function saveSettings() {
const settings = {
wifiSSID: document.getElementById('wifi-ssid').value.trim(),
wifiPassword: document.getElementById('wifi-password').value,
staEnable: document.getElementById('sta-enable').checked,
staSSID: document.getElementById('sta-ssid').value.trim(),
staPassword: document.getElementById('sta-password').value,
canMode: document.getElementById('can-mode').value,
bitRate: parseInt(document.getElementById('bit-rate').value),
dataRate: parseInt(document.getElementById('data-rate').value),
controllerMode: parseInt(document.getElementById('controller-mode').value)
};
// Validation
if (settings.wifiSSID.length === 0) {
alert('WiFi SSID를 .');
return;
}
if (settings.wifiPassword.length > 0 && settings.wifiPassword.length < 8) {
alert('WiFi 8 .');
return;
}
if (settings.staEnable && settings.staSSID.length === 0) {
alert('Station WiFi SSID를 .');
return;
}
fetch('/settings/save', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(settings)
})
.then(r => r.json())
.then(data => {
if (data.success) {
showAlert('alert-success', ' ! ESP32를 .', 'alert-success');
} else {
alert(' : ' + data.message);
}
})
.catch(err => {
alert(' : ' + err);
});
}
function toggleSTASettings() {
const staEnable = document.getElementById('sta-enable').checked;
const staSettings = document.getElementById('sta-settings');
if (staEnable) {
staSettings.classList.remove('disabled');
} else {
staSettings.classList.add('disabled');
}
}
function toggleDataRate() {
const canMode = document.getElementById('can-mode').value;
const dataRateGroup = document.getElementById('data-rate-group');
if (canMode === 'classic') {
dataRateGroup.style.display = 'none';
} else {
dataRateGroup.style.display = 'block';
}
}
function showAlert(alertId, message, className) {
const alert = document.getElementById(alertId);
if (alert) {
const textElement = alert.querySelector('.alert-text');
if (textElement && message) {
textElement.textContent = message;
}
alert.className = 'alert ' + className;
alert.classList.add('show');
if (className === 'alert-success') {
setTimeout(() => {
hideAlert(alertId);
}, 5000);
}
}
}
function hideAlert(alertId) {
const alert = document.getElementById(alertId);
if (alert) {
alert.classList.remove('show');
}
}
// Load settings on page load
window.addEventListener('load', function() {
showAlert('alert-loading', ' ...', 'alert-info');
loadSettings();
});
</script>
</body>
</html>
)rawliteral";
#endif