Remove deprecated HTML files and scripts, refactor API to support asynchronous requests, and improve WebSocket handling for scale actions.
This commit is contained in:
1 parent
823d1f8c7e
commit
13a0acf2ac
20 files changed
+260
-2147
No files matched your search
Vendored
BIN
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
@@ -1,43 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>FilaMan - Filament Management Tool</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.ico">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script>
|
||||
fetch('/api/version')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const versionSpan = document.querySelector('.version');
|
||||
if (versionSpan) {
|
||||
versionSpan.textContent = 'v' + data.version;
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Error fetching version:', error));
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar">
|
||||
<div style="display: flex; align-items: center; gap: 2rem;">
|
||||
<img src="/logo.png" alt="FilaMan Logo" class="logo">
|
||||
<div class="logo-text">
|
||||
<h1>FilaMan<span class="version"></span></h1>
|
||||
<h4>Filament Management Tool</h4>
|
||||
</div>
|
||||
</div>
|
||||
<nav style="display: flex; gap: 1rem;">
|
||||
<a href="/">Start</a>
|
||||
<a href="/waage">Scale</a>
|
||||
<a href="/setup">Setup</a>
|
||||
<a href="/upgrade">Upgrade</a>
|
||||
</nav>
|
||||
<div class="status-container">
|
||||
<div class="status-item">
|
||||
<span class="status-dot" id="filamanDot"></span>F
|
||||
</div>
|
||||
<div class="ram-status" id="ramStatus"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>FilaMan - Filament Management Tool</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.ico">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script>
|
||||
fetch('/api/version')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const versionSpan = document.querySelector('.version');
|
||||
if (versionSpan) {
|
||||
versionSpan.textContent = 'v' + data.version;
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Error fetching version:', error));
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar">
|
||||
<div style="display: flex; align-items: center; gap: 2rem;">
|
||||
<img src="/logo.png" alt="FilaMan Logo" class="logo">
|
||||
<div class="logo-text">
|
||||
<h1>FilaMan<span class="version"></span></h1>
|
||||
<h4>Filament Management Tool</h4>
|
||||
</div>
|
||||
</div>
|
||||
<nav style="display: flex; gap: 1rem;">
|
||||
<a href="/">Start</a>
|
||||
<a href="/waage">Scale</a>
|
||||
<a href="/config">Config</a>
|
||||
<a href="/about">About</a>
|
||||
<a href="/upgrade">Upgrade</a>
|
||||
</nav>
|
||||
<div class="status-container">
|
||||
<div class="status-item">
|
||||
<span class="status-dot" id="filamanDot"></span>F
|
||||
</div>
|
||||
<div class="ram-status" id="ramStatus"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1>FilaMan</h1>
|
||||
<p>Filament Management Tool</p>
|
||||
<p>Your smart solution for <strong>Filament Management</strong> in 3D printing.</p>
|
||||
|
||||
<h2>About FilaMan</h2>
|
||||
<p>
|
||||
FilaMan is a tool designed to simplify filament spool management. It allows you to identify and weigh filament spools,
|
||||
automatically syncing data with the FilaMan-System.
|
||||
</p>
|
||||
|
||||
<p>Get more information at <a href="https://www.filaman.app" target="_blank">https://www.filaman.app</a>.</p>
|
||||
|
||||
<div class="features">
|
||||
<div class="feature">
|
||||
<h3>Spool Identification</h3>
|
||||
<p>Easily identify filament spools using NFC tags.</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<h3>Automatic Syncing</h3>
|
||||
<p>Seamlessly update spool data with the FilaMan API for accurate tracking.</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<h3>Scale Integration</h3>
|
||||
<p>Built-in scale support for precise remaining weight calculation.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let ws = null;
|
||||
function connectWebSocket() {
|
||||
ws = new WebSocket(`ws://${window.location.hostname}/ws`);
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'heartbeat') {
|
||||
document.getElementById('filamanDot').style.backgroundColor = data.filaman_connected ? '#4caf50' : '#f44336';
|
||||
document.getElementById('ramStatus').textContent = data.freeHeap + ' KB free';
|
||||
}
|
||||
};
|
||||
ws.onclose = () => setTimeout(connectWebSocket, 2000);
|
||||
}
|
||||
connectWebSocket();
|
||||
setInterval(() => { if(ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({type:'heartbeat'})); }, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 8.6 KiB |
@@ -1,87 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>FilaMan - Setup</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.ico">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar">
|
||||
<div style="display: flex; align-items: center; gap: 2rem;">
|
||||
<img src="/logo.png" alt="FilaMan Logo" class="logo">
|
||||
<div class="logo-text">
|
||||
<h1>FilaMan</h1>
|
||||
<h4>Filament Management Tool</h4>
|
||||
</div>
|
||||
</div>
|
||||
<nav style="display: flex; gap: 1rem;">
|
||||
<a href="/">Start</a>
|
||||
<a href="/waage">Scale</a>
|
||||
<a href="/setup">Setup</a>
|
||||
<a href="/upgrade">Upgrade</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1>Device Setup</h1>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Registration</h5>
|
||||
<p>Status: <strong>{{registered}}</strong></p>
|
||||
<div class="form-group">
|
||||
<label for="filamanUrl">FilaMan API URL:</label>
|
||||
<input type="text" id="filamanUrl" class="form-control" value="{{filamanUrl}}" placeholder="http://192.168.1.10:8000">
|
||||
</div>
|
||||
<div class="form-group mt-2">
|
||||
<label for="deviceCode">Registration Code (6 digits):</label>
|
||||
<input type="text" id="deviceCode" class="form-control" maxlength="6" placeholder="123456">
|
||||
</div>
|
||||
<button id="registerBtn" class="btn btn-primary mt-3">Register Device</button>
|
||||
<div id="statusMessage" class="mt-3"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('registerBtn').addEventListener('click', () => {
|
||||
const url = document.getElementById('filamanUrl').value;
|
||||
const code = document.getElementById('deviceCode').value;
|
||||
const statusMessage = document.getElementById('statusMessage');
|
||||
|
||||
if (!url || !code) {
|
||||
statusMessage.innerHTML = 'Please provide both URL and Code';
|
||||
statusMessage.className = 'alert alert-danger';
|
||||
return;
|
||||
}
|
||||
|
||||
statusMessage.innerHTML = 'Registering...';
|
||||
statusMessage.className = 'alert alert-info';
|
||||
|
||||
fetch('/api/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: url, code: code })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
statusMessage.innerHTML = 'Registration successful! Rebooting...';
|
||||
statusMessage.className = 'alert alert-success';
|
||||
setTimeout(() => fetch('/reboot'), 2000);
|
||||
} else {
|
||||
statusMessage.innerHTML = 'Registration failed. Check code and URL.';
|
||||
statusMessage.className = 'alert alert-danger';
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
statusMessage.innerHTML = 'Network error.';
|
||||
statusMessage.className = 'alert alert-danger';
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-1207
File diff suppressed because it is too large.
Load diff
@@ -1,151 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>FilaMan - Filament Management Tool</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.ico">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script>
|
||||
fetch('/api/version')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const versionSpan = document.querySelector('.version');
|
||||
if (versionSpan) {
|
||||
versionSpan.textContent = 'v' + data.version;
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Error fetching version:', error));
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar">
|
||||
<div style="display: flex; align-items: center; gap: 2rem;">
|
||||
<img src="/logo.png" alt="FilaMan Logo" class="logo">
|
||||
<div class="logo-text">
|
||||
<h1>FilaMan<span class="version"></span></h1>
|
||||
<h4>Filament Management Tool</h4>
|
||||
</div>
|
||||
</div>
|
||||
<nav style="display: flex; gap: 1rem;">
|
||||
<a href="/">Start</a>
|
||||
<a href="/waage">Scale</a>
|
||||
<a href="/setup">Setup</a>
|
||||
<a href="/upgrade">Upgrade</a>
|
||||
</nav>
|
||||
<div class="status-container">
|
||||
<div class="status-item">
|
||||
<span class="status-dot" id="filamanDot"></span>F
|
||||
</div>
|
||||
<div class="ram-status" id="ramStatus"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1>Firmware Upgrade</h1>
|
||||
|
||||
<div class="warning">
|
||||
<strong>Warning:</strong> Do not power off the device during update.
|
||||
</div>
|
||||
|
||||
<div class="update-options">
|
||||
<div class="update-section">
|
||||
<h2>1) Firmware Update</h2>
|
||||
<p>Upload a new firmware file (upgrade_filaman_firmware_*.bin)</p>
|
||||
<div class="update-form">
|
||||
<form id="firmwareForm" enctype='multipart/form-data' data-type="firmware">
|
||||
<input type='file' name='update' accept='.bin' required>
|
||||
<input type='submit' value='Start Firmware Update' class="btn btn-primary">
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="update-section">
|
||||
<h2>2) Webpage Update</h2>
|
||||
<p>Upload a new webpage file (upgrade_filaman_website_*.bin)</p>
|
||||
<div class="update-form">
|
||||
<form id="webpageForm" enctype='multipart/form-data' data-type="webpage">
|
||||
<input type='file' name='update' accept='.bin' required>
|
||||
<input type='submit' value='Start Webpage Update' class="btn btn-primary">
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="progress-container" style="display: none;">
|
||||
<div class="progress-bar">0%</div>
|
||||
</div>
|
||||
<div class="status"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const progress = document.querySelector('.progress-bar');
|
||||
const progressContainer = document.querySelector('.progress-container');
|
||||
const status = document.querySelector('.status');
|
||||
let updateInProgress = false;
|
||||
let lastReceivedProgress = 0;
|
||||
|
||||
// WebSocket Handling
|
||||
let ws = null;
|
||||
function connectWebSocket() {
|
||||
ws = new WebSocket('ws://' + window.location.host + '/ws');
|
||||
ws.onmessage = function(event) {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === "heartbeat") {
|
||||
document.getElementById('filamanDot').style.backgroundColor = data.filaman_connected ? '#4caf50' : '#f44336';
|
||||
document.getElementById('ramStatus').textContent = data.freeHeap + ' KB free';
|
||||
}
|
||||
if (data.type === "updateProgress" && updateInProgress) {
|
||||
progressContainer.style.display = 'block';
|
||||
const newProgress = parseInt(data.progress);
|
||||
if (!isNaN(newProgress) && newProgress >= lastReceivedProgress) {
|
||||
progress.style.width = newProgress + '%';
|
||||
progress.textContent = newProgress + '%';
|
||||
lastReceivedProgress = newProgress;
|
||||
}
|
||||
if (data.message) {
|
||||
status.textContent = data.message;
|
||||
status.style.display = 'block';
|
||||
}
|
||||
}
|
||||
};
|
||||
ws.onclose = () => setTimeout(connectWebSocket, 2000);
|
||||
}
|
||||
connectWebSocket();
|
||||
|
||||
function handleUpdate(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const file = form.update.files[0];
|
||||
const updateType = form.dataset.type;
|
||||
|
||||
if (!file) return;
|
||||
|
||||
updateInProgress = true;
|
||||
progressContainer.style.display = 'block';
|
||||
status.style.display = 'none';
|
||||
progress.style.width = '0%';
|
||||
|
||||
document.querySelectorAll('form input[type=submit]').forEach(btn => btn.disabled = true);
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', '/update', true);
|
||||
xhr.onload = function() {
|
||||
if (xhr.status !== 200) {
|
||||
status.textContent = "Update failed: " + xhr.responseText;
|
||||
status.style.display = 'block';
|
||||
updateInProgress = false;
|
||||
document.querySelectorAll('form input[type=submit]').forEach(btn => btn.disabled = false);
|
||||
}
|
||||
};
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('update', file);
|
||||
xhr.send(formData);
|
||||
}
|
||||
|
||||
document.getElementById('firmwareForm').addEventListener('submit', handleUpdate);
|
||||
document.getElementById('webpageForm').addEventListener('submit', handleUpdate);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>FilaMan - Scale Configuration</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.ico">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script>
|
||||
fetch('/api/version')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const versionSpan = document.querySelector('.version');
|
||||
if (versionSpan) {
|
||||
versionSpan.textContent = 'v' + data.version;
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Error fetching version:', error));
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar">
|
||||
<div style="display: flex; align-items: center; gap: 2rem;">
|
||||
<img src="/logo.png" alt="FilaMan Logo" class="logo">
|
||||
<div class="logo-text">
|
||||
<h1>FilaMan<span class="version"></span></h1>
|
||||
<h4>Filament Management Tool</h4>
|
||||
</div>
|
||||
</div>
|
||||
<nav style="display: flex; gap: 1rem;">
|
||||
<a href="/">Start</a>
|
||||
<a href="/waage">Scale</a>
|
||||
<a href="/config">Config</a>
|
||||
<a href="/about">About</a>
|
||||
<a href="/upgrade">Upgrade</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1>Scale Configuration</h1>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Scale Actions</h5>
|
||||
<button id="calibrateBtn" class="btn btn-primary">Calibrate Scale</button>
|
||||
<button id="tareBtn" class="btn btn-secondary">Tare Scale</button>
|
||||
Enable Auto-TARE <input type="checkbox" id="autoTareCheckbox" onchange="setAutoTare(this.checked);" {{autoTare}}>
|
||||
<div id="statusMessage" class="mt-3"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="calibrationCard" class="card mt-3" style="display: none;">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Calibration Procedure</h5>
|
||||
<p>Please follow these steps:</p>
|
||||
<ol>
|
||||
<li>Make sure the scale is empty</li>
|
||||
<li>Have a 500g calibration weight ready</li>
|
||||
<li>Click on "Start Calibration"</li>
|
||||
<li>Step 1: Empty the scale</li>
|
||||
<li>Step 2: Place the 500g weight on the scale</li>
|
||||
<li>Step 3: Remove weight from Scale</li>
|
||||
</ol>
|
||||
<button id="startCalibrationBtn" class="btn btn-danger">Start Calibration</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let ws = null;
|
||||
const statusMessage = document.getElementById('statusMessage');
|
||||
|
||||
function connectWebSocket() {
|
||||
ws = new WebSocket(`ws://${window.location.hostname}/ws`);
|
||||
|
||||
ws.onopen = () => {
|
||||
statusMessage.innerHTML = 'Scale connected';
|
||||
enableButtons(true);
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
statusMessage.innerHTML = 'Scale connection lost';
|
||||
enableButtons(false);
|
||||
setTimeout(connectWebSocket, 2000);
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'scale') {
|
||||
if (data.payload === 'success') {
|
||||
statusMessage.innerHTML = 'Action successful';
|
||||
statusMessage.className = 'alert alert-success';
|
||||
} else if (data.payload === 'error') {
|
||||
statusMessage.innerHTML = 'Error while performing action';
|
||||
statusMessage.className = 'alert alert-danger';
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function enableButtons(enabled) {
|
||||
document.getElementById('calibrateBtn').disabled = !enabled;
|
||||
document.getElementById('tareBtn').disabled = !enabled;
|
||||
}
|
||||
|
||||
document.getElementById('calibrateBtn').addEventListener('click', () => {
|
||||
document.getElementById('calibrationCard').style.display = 'block';
|
||||
});
|
||||
|
||||
document.getElementById('startCalibrationBtn').addEventListener('click', () => {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'scale',
|
||||
payload: 'calibrate'
|
||||
}));
|
||||
document.getElementById('calibrationCard').style.display = 'none';
|
||||
});
|
||||
|
||||
document.getElementById('tareBtn').addEventListener('click', () => {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'scale',
|
||||
payload: 'tare'
|
||||
}));
|
||||
});
|
||||
|
||||
function setAutoTare(enabled) {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'scale',
|
||||
payload: 'setAutoTare',
|
||||
enabled: enabled
|
||||
}));
|
||||
}
|
||||
|
||||
connectWebSocket();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,67 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>FilaMan - Filament Management Tool</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.ico">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script>
|
||||
fetch('/api/version')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const versionSpan = document.querySelector('.version');
|
||||
if (versionSpan) {
|
||||
versionSpan.textContent = 'v' + data.version;
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Error fetching version:', error));
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar">
|
||||
<div style="display: flex; align-items: center; gap: 2rem;">
|
||||
<img src="/logo.png" alt="FilaMan Logo" class="logo">
|
||||
<div class="logo-text">
|
||||
<h1>FilaMan<span class="version"></span></h1>
|
||||
<h4>Filament Management Tool</h4>
|
||||
</div>
|
||||
</div>
|
||||
<nav style="display: flex; gap: 1rem;">
|
||||
<a href="/">Start</a>
|
||||
<a href="/waage">Scale</a>
|
||||
<a href="/setup">Setup</a>
|
||||
<a href="/upgrade">Upgrade</a>
|
||||
</nav>
|
||||
<div class="status-container">
|
||||
<div class="status-item">
|
||||
<span class="status-dot" id="filamanDot"></span>F
|
||||
</div>
|
||||
<div class="ram-status" id="ramStatus"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1>WiFi Configuration</h1>
|
||||
<p>Your device is connected to WiFi.</p>
|
||||
<p>To change WiFi settings, you can reset the WiFi configuration by holding the hardware button (if available) or using the WiFi manager portal.</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let ws = null;
|
||||
function connectWebSocket() {
|
||||
ws = new WebSocket(`ws://${window.location.hostname}/ws`);
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'heartbeat') {
|
||||
document.getElementById('filamanDot').style.backgroundColor = data.filaman_connected ? '#4caf50' : '#f44336';
|
||||
document.getElementById('ramStatus').textContent = data.freeHeap + ' KB free';
|
||||
}
|
||||
};
|
||||
ws.onclose = () => setTimeout(connectWebSocket, 2000);
|
||||
}
|
||||
connectWebSocket();
|
||||
setInterval(() => { if(ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({type:'heartbeat'})); }, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+2
-6
@@ -58,15 +58,11 @@ build_flags =
|
||||
-DCONFIG_LWIP_TCP_MSL=60000
|
||||
-DCONFIG_LWIP_TCP_RCV_BUF_DEFAULT=4096
|
||||
-DCONFIG_LWIP_MAX_ACTIVE_TCP=16
|
||||
-DCONFIG_ASYNC_TCP_RUNNING_CORE=0
|
||||
-DCONFIG_ASYNC_TCP_USE_WDT=0
|
||||
|
||||
extra_scripts =
|
||||
scripts/extra_script.py
|
||||
${env:buildfs.extra_scripts}
|
||||
|
||||
[env:buildfs]
|
||||
extra_scripts =
|
||||
pre:scripts/combine_html.py ; Combine header with HTML files
|
||||
scripts/gzip_files.py ; Compress files for SPIFFS
|
||||
|
||||
[platformio]
|
||||
default_envs = esp32dev
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
Import("env")
|
||||
import os
|
||||
import re
|
||||
|
||||
def combine_html_files(source, target, env):
|
||||
print("COMBINE HTML FILES")
|
||||
|
||||
html_dir = "./html"
|
||||
header_file = os.path.join(html_dir, "header.html")
|
||||
|
||||
# Read header content
|
||||
with open(header_file, 'r') as f:
|
||||
header_content = f.read()
|
||||
|
||||
# Process all HTML files except header.html
|
||||
for filename in os.listdir(html_dir):
|
||||
if filename.endswith('.html') and filename != 'header.html':
|
||||
file_path = os.path.join(html_dir, filename)
|
||||
|
||||
# Read content
|
||||
with open(file_path, 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
# Replace content between head comments with header content
|
||||
pattern = r'(<!-- head -->).*?(<!-- head -->)'
|
||||
new_content = re.sub(pattern, r'\1' + header_content + r'\2', content, flags=re.DOTALL)
|
||||
|
||||
# Write back combined content
|
||||
with open(file_path, 'w') as f:
|
||||
f.write(new_content)
|
||||
print(f"Combined header with {filename}")
|
||||
|
||||
# Register the script to run before building SPIFFS
|
||||
env.AddPreAction("buildfs", combine_html_files)
|
||||
@@ -1,48 +0,0 @@
|
||||
import gzip
|
||||
import os
|
||||
import shutil
|
||||
|
||||
## gzip files
|
||||
|
||||
def compress_file(input_file, output_file):
|
||||
with open(input_file, 'rb') as f_in:
|
||||
with gzip.open(output_file, 'wb') as f_out:
|
||||
f_out.writelines(f_in)
|
||||
|
||||
def copy_file(input_file, output_file):
|
||||
shutil.copy2(input_file, output_file)
|
||||
|
||||
def should_compress(file):
|
||||
# Skip compression for spoolman.html
|
||||
if file == 'spoolman.html' or file == 'waage.html':
|
||||
return False
|
||||
# Komprimiere nur bestimmte Dateitypen
|
||||
return file.endswith(('.js', '.png', '.css', '.html'))
|
||||
|
||||
def main(source_dir, target_dir):
|
||||
for root, dirs, files in os.walk(source_dir):
|
||||
rel_path = os.path.relpath(root, source_dir)
|
||||
for file in files:
|
||||
input_file = os.path.join(root, file)
|
||||
output_file_compressed = os.path.join(target_dir, rel_path, file + '.gz')
|
||||
output_file_original = os.path.join(target_dir, rel_path, file)
|
||||
|
||||
os.makedirs(os.path.dirname(output_file_compressed), exist_ok=True)
|
||||
|
||||
if should_compress(file):
|
||||
compress_file(input_file, output_file_compressed)
|
||||
print(f'Compressed {input_file} to {output_file_compressed}')
|
||||
else:
|
||||
copy_file(input_file, output_file_original)
|
||||
print(f'Copied {input_file} to {output_file_original}')
|
||||
|
||||
def init():
|
||||
source_dir = 'html'
|
||||
target_dir = 'data'
|
||||
|
||||
if os.path.exists(target_dir):
|
||||
shutil.rmtree(target_dir)
|
||||
|
||||
main(source_dir, target_dir)
|
||||
|
||||
init()
|
||||
+130
-78
@@ -12,6 +12,20 @@
|
||||
volatile filamanApiStateType filamanApiState = API_IDLE;
|
||||
bool filamanConnected = false;
|
||||
|
||||
struct ApiRequest {
|
||||
FilamanApiRequestType type;
|
||||
int id1;
|
||||
int id2;
|
||||
String str1;
|
||||
String str2;
|
||||
float val;
|
||||
bool active = false;
|
||||
};
|
||||
|
||||
#define MAX_API_QUEUE 10
|
||||
ApiRequest apiQueue[MAX_API_QUEUE];
|
||||
SemaphoreHandle_t queueMutex;
|
||||
|
||||
void saveFilamanConfig() {
|
||||
Preferences preferences;
|
||||
preferences.begin(NVS_NAMESPACE_API, false);
|
||||
@@ -36,136 +50,174 @@ bool checkFilamanRegistration() {
|
||||
|
||||
bool registerDevice(const String& deviceCode) {
|
||||
if (filamanUrl.length() == 0) return false;
|
||||
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/register";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(5000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/register");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("X-Device-Code", deviceCode);
|
||||
|
||||
int httpCode = http.POST("{}");
|
||||
bool success = false;
|
||||
|
||||
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_CREATED) {
|
||||
String payload = http.getString();
|
||||
if (httpCode == 200 || httpCode == 201) {
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
if (!error && doc["token"].is<String>()) {
|
||||
filamanToken = doc["token"].as<String>();
|
||||
filamanRegistered = true;
|
||||
saveFilamanConfig();
|
||||
success = true;
|
||||
Serial.println("Device successfully registered!");
|
||||
if (!deserializeJson(doc, http.getString())) {
|
||||
if (doc["token"].is<String>()) {
|
||||
filamanToken = doc["token"].as<String>();
|
||||
filamanRegistered = true;
|
||||
saveFilamanConfig();
|
||||
http.end();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Serial.printf("Registration failed, HTTP code: %d\n", httpCode);
|
||||
}
|
||||
|
||||
http.end();
|
||||
return success;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool sendHeartbeat() {
|
||||
if (!checkFilamanRegistration()) return false;
|
||||
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/heartbeat";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(3000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/heartbeat");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
|
||||
JsonDocument doc;
|
||||
doc["ip_address"] = WiFi.localIP().toString();
|
||||
String payload;
|
||||
serializeJson(doc, payload);
|
||||
|
||||
int httpCode = http.POST(payload);
|
||||
bool success = (httpCode == HTTP_CODE_OK);
|
||||
|
||||
if (success) {
|
||||
filamanConnected = true;
|
||||
} else {
|
||||
Serial.printf("Heartbeat failed, HTTP code: %d\n", httpCode);
|
||||
if (httpCode == 401) {
|
||||
filamanRegistered = false; // Token might be invalid
|
||||
saveFilamanConfig();
|
||||
}
|
||||
filamanConnected = false;
|
||||
}
|
||||
|
||||
filamanConnected = (httpCode == 200);
|
||||
http.end();
|
||||
return success;
|
||||
return filamanConnected;
|
||||
}
|
||||
|
||||
bool sendWeight(int spoolId, String tagUuid, float measuredWeight) {
|
||||
if (!checkFilamanRegistration()) return false;
|
||||
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/scale/weight";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(3000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/scale/weight");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
|
||||
JsonDocument doc;
|
||||
if (spoolId > 0) doc["spool_id"] = spoolId;
|
||||
if (tagUuid.length() > 0) doc["tag_uuid"] = tagUuid;
|
||||
doc["measured_weight_g"] = measuredWeight;
|
||||
|
||||
String payload;
|
||||
serializeJson(doc, payload);
|
||||
|
||||
int httpCode = http.POST(payload);
|
||||
bool success = (httpCode == HTTP_CODE_OK);
|
||||
|
||||
if (!success) {
|
||||
Serial.printf("Weight update failed, HTTP code: %d\n", httpCode);
|
||||
}
|
||||
|
||||
http.end();
|
||||
return success;
|
||||
return (httpCode == 200);
|
||||
}
|
||||
|
||||
bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid) {
|
||||
if (!checkFilamanRegistration()) return false;
|
||||
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/scale/locate";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(3000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/scale/locate");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
|
||||
JsonDocument doc;
|
||||
if (spoolId > 0) doc["spool_id"] = spoolId;
|
||||
if (spoolTagUuid.length() > 0) doc["spool_tag_uuid"] = spoolTagUuid;
|
||||
if (locationId > 0) doc["location_id"] = locationId;
|
||||
if (locationTagUuid.length() > 0) doc["location_tag_uuid"] = locationTagUuid;
|
||||
|
||||
String payload;
|
||||
serializeJson(doc, payload);
|
||||
|
||||
int httpCode = http.POST(payload);
|
||||
bool success = (httpCode == HTTP_CODE_OK);
|
||||
|
||||
if (!success) {
|
||||
Serial.printf("Location update failed, HTTP code: %d\n", httpCode);
|
||||
}
|
||||
|
||||
http.end();
|
||||
return success;
|
||||
return (httpCode == 200);
|
||||
}
|
||||
|
||||
void filamanApiTask(void* pvParameters) {
|
||||
for (;;) {
|
||||
ApiRequest req;
|
||||
bool hasReq = false;
|
||||
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) {
|
||||
if(apiQueue[i].active) {
|
||||
req = apiQueue[i];
|
||||
apiQueue[i].active = false;
|
||||
hasReq = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
|
||||
if (hasReq) {
|
||||
filamanApiState = API_TRANSMITTING;
|
||||
switch (req.type) {
|
||||
case API_REQUEST_HEARTBEAT: sendHeartbeat(); break;
|
||||
case API_REQUEST_WEIGHT: sendWeight(req.id1, req.str1, req.val); break;
|
||||
case API_REQUEST_LOCATE: sendLocation(req.id1, req.str1, req.id2, req.str2); break;
|
||||
default: break;
|
||||
}
|
||||
filamanApiState = API_IDLE;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
}
|
||||
}
|
||||
|
||||
void sendHeartbeatAsync() {
|
||||
if (!checkFilamanRegistration()) return;
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
|
||||
// Prevent duplicate heartbeats
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(apiQueue[i].active && apiQueue[i].type == API_REQUEST_HEARTBEAT) {
|
||||
xSemaphoreGive(queueMutex);
|
||||
return;
|
||||
}
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(!apiQueue[i].active) {
|
||||
apiQueue[i].type = API_REQUEST_HEARTBEAT;
|
||||
apiQueue[i].id1 = 0;
|
||||
apiQueue[i].id2 = 0;
|
||||
apiQueue[i].str1 = "";
|
||||
apiQueue[i].str2 = "";
|
||||
apiQueue[i].val = 0.0f;
|
||||
apiQueue[i].active = true;
|
||||
break;
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
}
|
||||
|
||||
void sendWeightAsync(int spoolId, String tagUuid, float weight) {
|
||||
if (!checkFilamanRegistration()) return;
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(!apiQueue[i].active) {
|
||||
apiQueue[i].type = API_REQUEST_WEIGHT;
|
||||
apiQueue[i].id1 = spoolId;
|
||||
apiQueue[i].id2 = 0;
|
||||
apiQueue[i].str1 = tagUuid;
|
||||
apiQueue[i].str2 = "";
|
||||
apiQueue[i].val = weight;
|
||||
apiQueue[i].active = true;
|
||||
break;
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
}
|
||||
|
||||
void sendLocationAsync(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid) {
|
||||
if (!checkFilamanRegistration()) return;
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(!apiQueue[i].active) {
|
||||
apiQueue[i].type = API_REQUEST_LOCATE;
|
||||
apiQueue[i].id1 = spoolId;
|
||||
apiQueue[i].id2 = locationId;
|
||||
apiQueue[i].str1 = spoolTagUuid;
|
||||
apiQueue[i].str2 = locationTagUuid;
|
||||
apiQueue[i].val = 0.0f;
|
||||
apiQueue[i].active = true;
|
||||
break;
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
}
|
||||
|
||||
bool initFilaman() {
|
||||
oledShowProgressBar(3, 7, DISPLAY_BOOT_TEXT, "FilaMan init");
|
||||
loadFilamanConfig();
|
||||
|
||||
if (checkFilamanRegistration()) {
|
||||
sendHeartbeat();
|
||||
}
|
||||
|
||||
oledShowTopRow();
|
||||
queueMutex = xSemaphoreCreateMutex();
|
||||
// Reduce stack size to 6k and set priority to 0 (lowest) to prevent starving WiFi stack
|
||||
xTaskCreatePinnedToCore(filamanApiTask, "FilaManApi", 6144, NULL, 0, NULL, 0);
|
||||
if (checkFilamanRegistration()) sendHeartbeatAsync();
|
||||
return true;
|
||||
}
|
||||
@@ -25,6 +25,11 @@ extern bool filamanConnected;
|
||||
// FilaMan API functions
|
||||
bool initFilaman();
|
||||
bool registerDevice(const String& deviceCode);
|
||||
void sendHeartbeatAsync();
|
||||
void sendWeightAsync(int spoolId, String tagUuid, float weight);
|
||||
void sendLocationAsync(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid);
|
||||
|
||||
// Internal blocking functions (used by async task)
|
||||
bool sendHeartbeat();
|
||||
bool sendWeight(int spoolId, String tagUuid, float weight);
|
||||
bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid);
|
||||
|
||||
+7
-9
@@ -124,7 +124,7 @@ void loop() {
|
||||
// Periodic FilaMan heartbeat
|
||||
if (intervalElapsed(currentMillis, lastFilamanHeartbeatTime, FILAMAN_HEARTBEAT_INTERVAL))
|
||||
{
|
||||
sendHeartbeat();
|
||||
sendHeartbeatAsync();
|
||||
}
|
||||
|
||||
// If scale is not calibrated, only show a warning
|
||||
@@ -190,10 +190,9 @@ void loop() {
|
||||
// Get UID from nfcJsonData or similar (nfc.cpp should set it)
|
||||
// For now, use activeSpoolId if available
|
||||
int sId = activeSpoolId.toInt();
|
||||
if (sendWeight(sId, activeTagUuid, weight)) {
|
||||
weightSend = 1;
|
||||
Serial.println("Weight sent to FilaMan");
|
||||
}
|
||||
sendWeightAsync(sId, activeTagUuid, weight);
|
||||
weightSend = 1;
|
||||
Serial.println("Weight queued for FilaMan");
|
||||
}
|
||||
|
||||
// Handle successful tag write
|
||||
@@ -201,10 +200,9 @@ void loop() {
|
||||
{
|
||||
tagProcessed = true;
|
||||
int sId = activeSpoolId.toInt();
|
||||
if (sendWeight(sId, activeTagUuid, weight)) {
|
||||
weightSend = 1;
|
||||
Serial.println("Weight sent to FilaMan after tag write");
|
||||
}
|
||||
sendWeightAsync(sId, activeTagUuid, weight);
|
||||
weightSend = 1;
|
||||
Serial.println("Weight queued for FilaMan after tag write");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-13
@@ -1268,7 +1268,7 @@ bool decodeNdefAndReturnJson(const byte* encodedMessage, String uidString) {
|
||||
Serial.println("Location Tag found!");
|
||||
int locId = doc["location_id"].as<int>();
|
||||
int sId = lastSpoolId.toInt();
|
||||
sendLocation(sId, "", locId, "");
|
||||
sendLocationAsync(sId, "", locId, "");
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1867,15 +1867,6 @@ void scanRfidTask(void * parameter) {
|
||||
|
||||
foundNfcTag(nullptr, success);
|
||||
|
||||
// Reset activeSpoolId and activeTagUuid immediately when no tag is detected
|
||||
if (!success) {
|
||||
activeSpoolId = "";
|
||||
activeTagUuid = "";
|
||||
Serial.println("Tag entfernt");
|
||||
oledShowWeight(weight);
|
||||
}
|
||||
|
||||
|
||||
// As long as there is still a tag on the reader, do not try to read it again
|
||||
if (success && nfcReaderState == NFC_IDLE)
|
||||
{
|
||||
@@ -1989,12 +1980,11 @@ void scanRfidTask(void * parameter) {
|
||||
|
||||
if (!success && nfcReaderState != NFC_IDLE && !nfcReadingTaskSuspendRequest)
|
||||
{
|
||||
Serial.printf("NFC: Tag removed (Previous state: %d)\n", nfcReaderState);
|
||||
nfcReaderState = NFC_IDLE;
|
||||
//uidString = "";
|
||||
nfcJsonData = "";
|
||||
activeSpoolId = "";
|
||||
activeTagUuid = "";
|
||||
Serial.println("Tag entfernt");
|
||||
oledShowWeight(weight);
|
||||
}
|
||||
|
||||
@@ -2012,7 +2002,7 @@ void scanRfidTask(void * parameter) {
|
||||
// Reduced from 5 seconds to 3 seconds
|
||||
} else {
|
||||
// Faster scanning when no tag or idle state
|
||||
vTaskDelay(pdMS_TO_TICKS(150));
|
||||
vTaskDelay(pdMS_TO_TICKS(250));
|
||||
// Faster scan interval
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -1,4 +1,5 @@
|
||||
#include "nfc.h"
|
||||
#include "scale.h"
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include "config.h"
|
||||
@@ -35,6 +36,7 @@ uint8_t pauseMainTask = 0;
|
||||
bool scaleCalibrated;
|
||||
bool autoTare = true;
|
||||
bool scaleCalibrationActive = false;
|
||||
volatile bool scaleCalibrationRequest = false;
|
||||
|
||||
// ##### Weight stabilization functions #####
|
||||
|
||||
@@ -178,6 +180,12 @@ void scale_loop(void * parameter) {
|
||||
weight = 0; // Reset global weight variable after tare
|
||||
}
|
||||
|
||||
// Check for calibration request
|
||||
if (scaleCalibrationRequest) {
|
||||
scaleCalibrationRequest = false;
|
||||
calibrate_scale();
|
||||
}
|
||||
|
||||
// Get raw weight reading
|
||||
float rawWeight = scale.get_units();
|
||||
|
||||
@@ -286,7 +294,8 @@ uint8_t calibrate_scale() {
|
||||
scaleCalibrationActive = true;
|
||||
|
||||
if (RfidReaderTask != NULL) vTaskSuspend(RfidReaderTask);
|
||||
if (ScaleTask != NULL) vTaskSuspend(ScaleTask);
|
||||
// Do not suspend ScaleTask if we are running inside it
|
||||
if (ScaleTask != NULL && xTaskGetCurrentTaskHandle() != ScaleTask) vTaskSuspend(ScaleTask);
|
||||
|
||||
pauseMainTask = 1;
|
||||
|
||||
@@ -393,7 +402,7 @@ uint8_t calibrate_scale() {
|
||||
}
|
||||
|
||||
if (RfidReaderTask != NULL) vTaskResume(RfidReaderTask);
|
||||
if (ScaleTask != NULL) vTaskResume(ScaleTask);
|
||||
if (ScaleTask != NULL && xTaskGetCurrentTaskHandle() != ScaleTask) vTaskResume(ScaleTask);
|
||||
pauseMainTask = 0;
|
||||
scaleCalibrationActive = false;
|
||||
|
||||
|
||||
+4
-3
@@ -5,7 +5,7 @@
|
||||
#include "HX711.h"
|
||||
|
||||
uint8_t setAutoTare(bool autoTareValue);
|
||||
uint8_t start_scale(bool touchSensorConnected);
|
||||
void start_scale(bool touchSensorConnected);
|
||||
uint8_t calibrate_scale();
|
||||
uint8_t tareScale();
|
||||
|
||||
@@ -20,12 +20,13 @@ extern HX711 scale;
|
||||
extern int16_t weight;
|
||||
extern uint8_t weightCounterToApi;
|
||||
extern uint8_t scale_tare_counter;
|
||||
extern uint8_t scaleTareRequest;
|
||||
extern bool scaleTareRequest;
|
||||
extern uint8_t pauseMainTask;
|
||||
extern bool scaleCalibrated;
|
||||
extern bool autoTare;
|
||||
extern bool scaleCalibrationActive;
|
||||
extern volatile bool scaleCalibrationRequest;
|
||||
|
||||
extern TaskHandle_t ScaleTask;
|
||||
|
||||
#endif
|
||||
#endif
|
||||
+98
-172
@@ -16,8 +16,7 @@
|
||||
#define VERSION "1.2.0"
|
||||
#endif
|
||||
|
||||
// Cache-Control Header definieren
|
||||
#define CACHE_CONTROL "max-age=604800" // Cache für 1 Woche
|
||||
#define NO_CACHE "no-cache, no-store, must-revalidate"
|
||||
|
||||
AsyncWebServer server(webserverPort);
|
||||
AsyncWebSocket ws("/ws");
|
||||
@@ -25,43 +24,26 @@ AsyncWebSocket ws("/ws");
|
||||
uint8_t lastSuccess = 0;
|
||||
nfcReaderStateType lastnfcReaderState = NFC_IDLE;
|
||||
|
||||
|
||||
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
|
||||
HEAP_DEBUG_MESSAGE("onWsEvent begin");
|
||||
if (type == WS_EVT_CONNECT) {
|
||||
Serial.println("Neuer Client verbunden!");
|
||||
Serial.printf("WS Client #%u connected\n", client->id());
|
||||
sendNfcData();
|
||||
foundNfcTag(client, 0);
|
||||
sendWriteResult(client, 3);
|
||||
|
||||
// Clean up dead connections
|
||||
(*server).cleanupClients();
|
||||
Serial.println("Currently connected number of clients: " + String((*server).getClients().size()));
|
||||
} else if (type == WS_EVT_DISCONNECT) {
|
||||
Serial.println("Client getrennt.");
|
||||
} else if (type == WS_EVT_ERROR) {
|
||||
Serial.printf("WebSocket Client #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
|
||||
} else if (type == WS_EVT_PONG) {
|
||||
Serial.printf("WebSocket Client #%u pong\n", client->id());
|
||||
ws.text(client->id(), "{\"type\":\"nfcTag\", \"payload\":{\"found\": " + String(lastSuccess) + "}}");
|
||||
server->cleanupClients();
|
||||
} else if (type == WS_EVT_DATA) {
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, (char*)data, len);
|
||||
|
||||
if (error) {
|
||||
Serial.println("JSON deserialization failed: " + String(error.c_str()));
|
||||
return;
|
||||
}
|
||||
if (error) return;
|
||||
|
||||
if (doc["type"] == "heartbeat") {
|
||||
// Sende Heartbeat-Antwort
|
||||
ws.text(client->id(), "{"
|
||||
"\"type\":\"heartbeat\","
|
||||
"\"freeHeap\":" + String(ESP.getFreeHeap()/1024) + ","
|
||||
"\"filaman_connected\":" + String(filamanConnected) + ","
|
||||
"\"registered\":" + String(filamanRegistered) + ""
|
||||
"\"registered\":" + String(filamanRegistered) + ","
|
||||
"\"autoTare\":" + String(autoTare ? "true" : "false") + ""
|
||||
"}");
|
||||
}
|
||||
|
||||
else if (doc["type"] == "writeNfcTag") {
|
||||
if (doc["payload"].is<JsonObject>()) {
|
||||
String payloadString;
|
||||
@@ -69,222 +51,166 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp
|
||||
startWriteJsonToTag((doc["tagType"] == "spool") ? true : false, payloadString.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
else if (doc["type"] == "scale") {
|
||||
uint8_t success = 0;
|
||||
if (doc["payload"] == "tare") {
|
||||
scaleTareRequest = true;
|
||||
success = 1;
|
||||
}
|
||||
|
||||
if (doc["payload"] == "calibrate") {
|
||||
success = calibrate_scale();
|
||||
}
|
||||
|
||||
if (doc["payload"] == "setAutoTare") {
|
||||
success = setAutoTare(doc["enabled"].as<bool>());
|
||||
}
|
||||
|
||||
if (success) {
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"success\"}");
|
||||
} else {
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"error\"}");
|
||||
}
|
||||
else if (doc["payload"] == "calibrate") {
|
||||
scaleCalibrationRequest = true;
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"success\"}");
|
||||
}
|
||||
else if (doc["payload"] == "setAutoTare") {
|
||||
setAutoTare(doc["enabled"].as<bool>());
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"success\"}");
|
||||
}
|
||||
}
|
||||
|
||||
else if (doc["type"] == "reconnect") {
|
||||
if (doc["payload"] == "filaman") {
|
||||
sendHeartbeat();
|
||||
sendHeartbeatAsync();
|
||||
}
|
||||
}
|
||||
|
||||
else {
|
||||
Serial.println("Unbekannter WebSocket-Typ: " + doc["type"].as<String>());
|
||||
}
|
||||
doc.clear();
|
||||
}
|
||||
HEAP_DEBUG_MESSAGE("onWsEvent end");
|
||||
}
|
||||
|
||||
String loadHtmlWithHeader(const char* filename) {
|
||||
Serial.println("Lade HTML-Datei: " + String(filename));
|
||||
if (!LittleFS.exists(filename)) {
|
||||
Serial.println("Fehler: Datei nicht gefunden!");
|
||||
return "Fehler: Datei nicht gefunden!";
|
||||
}
|
||||
|
||||
File file = LittleFS.open(filename, "r");
|
||||
String html = file.readString();
|
||||
file.close();
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
void sendWriteResult(AsyncWebSocketClient *client, uint8_t success) {
|
||||
String response = "{\"type\":\"writeNfcTag\",\"success\":" + String(success ? "1" : "0") + "}";
|
||||
ws.textAll(response);
|
||||
if (client) client->text(response); else ws.textAll(response);
|
||||
}
|
||||
|
||||
void foundNfcTag(AsyncWebSocketClient *client, uint8_t success) {
|
||||
if (success == lastSuccess) return;
|
||||
if (success == lastSuccess && client == nullptr) return;
|
||||
ws.textAll("{\"type\":\"nfcTag\", \"payload\":{\"found\": " + String(success) + "}}");
|
||||
sendNfcData();
|
||||
lastSuccess = success;
|
||||
}
|
||||
|
||||
void sendNfcData() {
|
||||
if (lastnfcReaderState == nfcReaderState) return;
|
||||
switch(nfcReaderState){
|
||||
case NFC_IDLE:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}");
|
||||
break;
|
||||
case NFC_READ_SUCCESS:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":" + nfcJsonData + "}");
|
||||
break;
|
||||
case NFC_READ_ERROR:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Empty Tag or Data not readable\"}}");
|
||||
break;
|
||||
case NFC_WRITING:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Schreibe Tag...\"}}");
|
||||
break;
|
||||
case NFC_WRITE_SUCCESS:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Tag erfolgreich geschrieben\"}}");
|
||||
break;
|
||||
case NFC_WRITE_ERROR:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Error writing to Tag\"}}");
|
||||
break;
|
||||
case DEFAULT:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Something went wrong\"}}");
|
||||
case NFC_IDLE: ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}"); break;
|
||||
case NFC_READ_SUCCESS: ws.textAll("{\"type\":\"nfcData\", \"payload\":" + nfcJsonData + "}"); break;
|
||||
case NFC_READ_ERROR: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Read Error\"}}"); break;
|
||||
case NFC_WRITING: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Writing...\"}}"); break;
|
||||
case NFC_WRITE_SUCCESS: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Success\"}}"); break;
|
||||
case NFC_WRITE_ERROR: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Write Error\"}}"); break;
|
||||
default: break;
|
||||
}
|
||||
lastnfcReaderState = nfcReaderState;
|
||||
}
|
||||
|
||||
void setupWebserver(AsyncWebServer &server) {
|
||||
oledShowProgressBar(2, 7, DISPLAY_BOOT_TEXT, "Webserver init");
|
||||
Serial.setDebugOutput(false);
|
||||
|
||||
ws.onEvent(onWsEvent);
|
||||
ws.enable(true);
|
||||
server.addHandler(&ws);
|
||||
|
||||
server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){});
|
||||
server.onFileUpload([](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final){});
|
||||
|
||||
loadFilamanConfig();
|
||||
|
||||
// Route für Start (Index)
|
||||
// Static Routes
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String html = loadHtmlWithHeader("/index.html");
|
||||
request->send(200, "text/html", html);
|
||||
Serial.println("Web: Request /");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/index.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// Route für Waage
|
||||
server.on("/waage", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String html = loadHtmlWithHeader("/waage.html");
|
||||
html.replace("{{autoTare}}", (autoTare) ? "checked" : "");
|
||||
request->send(200, "text/html", html);
|
||||
Serial.println("Web: Request /waage");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/waage.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// Route für Setup & Registration
|
||||
server.on("/setup", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String html = loadHtmlWithHeader("/setup.html");
|
||||
html.replace("{{filamanUrl}}", filamanUrl);
|
||||
html.replace("{{registered}}", filamanRegistered ? "Yes" : "No");
|
||||
request->send(200, "text/html", html);
|
||||
Serial.println("Web: Request /setup");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/setup.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /wifi");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/wifi.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
Serial.println("Web: Request /upgrade");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/upgrade.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/style.css", "text/css");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/logo.png", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/logo.png", "image/png");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/favicon.ico", "image/x-icon");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// API Routes
|
||||
server.on("/api/config", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
JsonDocument doc;
|
||||
doc["url"] = filamanUrl;
|
||||
doc["registered"] = filamanRegistered;
|
||||
String response;
|
||||
serializeJson(doc, response);
|
||||
request->send(200, "application/json", response);
|
||||
});
|
||||
|
||||
server.on("/api/register", HTTP_POST, [](AsyncWebServerRequest *request){}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
|
||||
JsonDocument doc;
|
||||
deserializeJson(doc, (const char*)data);
|
||||
|
||||
DeserializationError error = deserializeJson(doc, (const uint8_t*)data, len);
|
||||
if (error) {
|
||||
request->send(400, "application/json", "{\"success\": false, \"error\": \"Invalid JSON\"}");
|
||||
return;
|
||||
}
|
||||
if (doc["url"].is<String>()) filamanUrl = doc["url"].as<String>();
|
||||
String code = doc["code"].as<String>();
|
||||
|
||||
saveFilamanConfig();
|
||||
|
||||
if (registerDevice(code)) {
|
||||
if (registerDevice(doc["code"].as<String>())) {
|
||||
request->send(200, "application/json", "{\"success\": true}");
|
||||
} else {
|
||||
request->send(400, "application/json", "{\"success\": false}");
|
||||
}
|
||||
});
|
||||
|
||||
// API for Backend to trigger Tag write
|
||||
server.on("/api/v1/rfid/write", HTTP_POST, [](AsyncWebServerRequest *request){}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
|
||||
// Check Authorization? (TBD)
|
||||
JsonDocument doc;
|
||||
deserializeJson(doc, (const char*)data);
|
||||
|
||||
DeserializationError error = deserializeJson(doc, (const uint8_t*)data, len);
|
||||
if (error) {
|
||||
request->send(400, "application/json", "{\"success\": false, \"error\": \"Invalid JSON\"}");
|
||||
return;
|
||||
}
|
||||
String payloadString;
|
||||
serializeJson(doc, payloadString);
|
||||
|
||||
bool isSpool = !doc["spool_id"].isNull();
|
||||
startWriteJsonToTag(isSpool, payloadString.c_str());
|
||||
|
||||
startWriteJsonToTag(!doc["spool_id"].isNull(), payloadString.c_str());
|
||||
request->send(200, "application/json", "{\"status\": \"writing\"}");
|
||||
});
|
||||
|
||||
// Route für WiFi
|
||||
server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/wifi.html.gz", "text/html");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
server.on("/api/version", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "application/json", "{\"version\": \"" VERSION "\"}");
|
||||
});
|
||||
|
||||
server.on("/reboot", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "text/plain", "Rebooting...");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
});
|
||||
|
||||
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/style.css.gz", "text/css");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/logo.png", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/logo.png.gz", "image/png");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/favicon.ico", "image/x-icon");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/rfid.js", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS,"/rfid.js.gz", "text/javascript");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/upgrade.html.gz", "text/html");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", "no-store");
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
handleUpdate(server);
|
||||
|
||||
server.on("/api/version", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String fm_version = VERSION;
|
||||
String jsonResponse = "{\"version\": \""+ fm_version +"\"}";
|
||||
request->send(200, "application/json", jsonResponse);
|
||||
});
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest *request){
|
||||
request->send(404, "text/plain", "Seite nicht gefunden");
|
||||
request->send(404, "text/plain", "Not found");
|
||||
});
|
||||
|
||||
ws.onEvent(onWsEvent);
|
||||
server.addHandler(&ws);
|
||||
ws.enable(true);
|
||||
|
||||
server.begin();
|
||||
Serial.println("Webserver gestartet");
|
||||
}
|
||||
Reference in new issue
Block a user