Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
216 changes: 145 additions & 71 deletions static/js/runTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,83 +2,157 @@ import state from './state.js';
import { initGauge, updateGauge } from './gauge.js';

const runBtn = document.getElementById('runBtn');
const stopBtn = document.getElementById('stopBtn');
const continuousToggle = document.getElementById('continuousToggle');
const resultEl = document.getElementById('result');
runBtn.addEventListener('click', async () => {
const target = state.ip;
const port = state.port;
const streams = state.streams;
let bandwidth = state.bandwidth.trim();
const protocol = state.protocol;
const mode = state.mode;
const units = state.units;
console.log(target, port, streams, bandwidth, protocol, mode, units)
const statusEl = document.querySelector('.status');
const avgEl = document.querySelector('.avg_speed');
const maxEl = document.querySelector('.max_speed');

let eventSource = null;
let isRunning = false;
let shouldLoop = false;
stopBtn.disabled = true;

const getAverage = () =>
state.bandwidthCount > 0
? (state.bandwidthSum / state.bandwidthCount).toFixed(2)
: 0;

const resetStats = () => {
state.bandwidthSum = 0;
state.bandwidthCount = 0;
state.maxBandwidth = 0;
};

const buildPayload = () => {
const payload = {
target: state.ip,
port: state.port,
streams: state.streams,
bandwidth: state.bandwidth.trim(),
protocol: state.protocol,
mode: state.mode,
units: state.units,
};

const regex = /^\d+(\.\d+)?[KMG]$/i;
if (!regex.test(payload.bandwidth)) payload.bandwidth = '0';
return payload;
};

const regex = /^\d+(\.\d+)?[KMG]$/i;
async function runSingleTest(runNumber) {
resetStats();
initGauge();

if (!regex.test(bandwidth)) bandwidth = "0";
if (runNumber === 1) {
resultEl.textContent = 'Running iPerf3...\n';
} else {
resultEl.textContent += `\n--- Run ${runNumber} ---\n`;
}
statusEl.textContent = 'Running';

resultEl.textContent = "Running iPerf3...\n";
state.bandwidthSum = 0;
state.bandwidthCount = 0;
state.maxBandwidth = 0;
initGauge();
const payload = buildPayload();

return new Promise(async (resolve, reject) => {
try {
const response = await fetch('/run_iperf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ protocol, mode, streams, target, bandwidth, port, units })
});

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Error starting iPerf3.');
}

let eventSource = new EventSource('/stream_iperf');

eventSource.onmessage = (event) => {
if (parseFloat(event.data) < 0) {
document.querySelector(".status").textContent = "Complete";
eventSource.close();
// return;
}

const avg = state.bandwidthCount > 0 ? (state.bandwidthSum / state.bandwidthCount).toFixed(2) : 0;
if (event.data === "--- TEST COMPLETED ---") {
resultEl.textContent += "Test completed successfully.\n";
eventSource.close();
}
else if (event.data === "server is busy"){
document.querySelector(".status").textContent = "Server is Busy";
}
else {
let bandwidthValue = parseFloat(event.data);
if (!isNaN(bandwidthValue)) {
if (bandwidthValue >= 0) {
updateGauge(bandwidthValue);
state.bandwidthSum += bandwidthValue;
state.bandwidthCount += 1;
if (bandwidthValue > state.maxBandwidth) state.maxBandwidth = bandwidthValue;

document.querySelector(".status").textContent = "Running";
resultEl.textContent += event.data + '\n';
} else {
document.querySelector(".status").textContent = "Complete";
document.querySelector(".avg_speed").textContent = `${avg} ${units}`;
document.querySelector(".max_speed").textContent = `${state.maxBandwidth} ${units}`;
}
}
}
};

eventSource.onerror = (error) => {
console.error("Stream error:", error);
resultEl.textContent = "Error occurred while streaming the output.";
eventSource.close();
};
const response = await fetch('/run_iperf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Error starting iPerf3.');
}
} catch (error) {
console.error("Stream error:", error);
resultEl.textContent = error.message;
reject(error);
return;
}

eventSource = new EventSource('/stream_iperf');

const cleanupStream = () => {
if (eventSource) {
eventSource.close();
eventSource = null;
}
};

const finalizeRun = () => {
cleanupStream();
const avg = getAverage();
avgEl.textContent = `${avg} ${state.units}`;
maxEl.textContent = `${state.maxBandwidth} ${state.units}`;
statusEl.textContent =
shouldLoop && state.continuousMode
? 'Starting next run...'
: 'Complete';
resolve();
};

eventSource.onmessage = (event) => {
if (parseFloat(event.data) < 0 || event.data === '--- TEST COMPLETED ---') {
finalizeRun();
return;
}

if (event.data === 'server is busy') {
statusEl.textContent = 'Server is Busy';
return;
}

const bandwidthValue = parseFloat(event.data);
if (!isNaN(bandwidthValue) && bandwidthValue >= 0) {
updateGauge(bandwidthValue);
state.bandwidthSum += bandwidthValue;
state.bandwidthCount += 1;
if (bandwidthValue > state.maxBandwidth) state.maxBandwidth = bandwidthValue;

statusEl.textContent = 'Running';
resultEl.textContent += `${event.data}\n`;
}
};

eventSource.onerror = () => {
cleanupStream();
reject(new Error('Error occurred while streaming the output.'));
};
});
}

runBtn.addEventListener('click', async () => {
if (isRunning) return;

shouldLoop = state.continuousMode;
isRunning = true;
runBtn.disabled = true;
stopBtn.disabled = false;
avgEl.textContent = '--';
maxEl.textContent = '--';

let runCounter = 1;

try {
do {
await runSingleTest(runCounter);
runCounter += 1;
} while (shouldLoop && state.continuousMode);
} catch (error) {
statusEl.textContent = 'Error';
resultEl.textContent = error.message;
} finally {
isRunning = false;
runBtn.disabled = false;
stopBtn.disabled = true;
shouldLoop = false;
}
});

stopBtn.addEventListener('click', () => {
shouldLoop = false;
state.continuousMode = false;
continuousToggle.checked = false;
statusEl.textContent = 'Stopping after current run';
});
10 changes: 9 additions & 1 deletion static/js/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const state = {
mode: 'download', // Default mode
units: 'Mbps', // Default unit
speedtest_state: 'READY', // Test state: READY or RUNNING
continuousMode: false, // Whether to repeat tests continuously

bandwidthSum: 0, // Sum of bandwidth values
bandwidthCount: 0, // Count of bandwidth samples
Expand Down Expand Up @@ -63,6 +64,13 @@ export default {
state.units = value;
},

get continuousMode() {
return state.continuousMode;
},
set continuousMode(value) {
state.continuousMode = value;
},

get speedtest_state() {
return state.speedtest_state;
},
Expand Down Expand Up @@ -98,4 +106,4 @@ export default {
}
};



4 changes: 4 additions & 0 deletions static/js/uiHandlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ document.getElementById('bandwidth').addEventListener('input', () => {
// console.log('Updated bandwidth:', state.bandwidth);
});

document.getElementById('continuousToggle').addEventListener('change', (event) => {
state.continuousMode = event.target.checked;
});



document.getElementById('uploadBtn').addEventListener('click', () => {
Expand Down
95 changes: 63 additions & 32 deletions static/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -275,19 +275,32 @@ header {
margin-bottom: 0;
}

label {
display: block;
font-size: 0.95rem;
font-weight: 600;
color: var(--text);
margin-bottom: 0.5rem;
}

.hint {
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.5);
font-weight: 400;
}
label {
display: block;
font-size: 0.95rem;
font-weight: 600;
color: var(--text);
margin-bottom: 0.5rem;
}

.hint {
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.5);
font-weight: 400;
}

.checkbox-toggle {
display: flex;
align-items: center;
gap: 0.6rem;
font-weight: 600;
}

.checkbox-toggle input[type="checkbox"] {
width: 18px;
height: 18px;
accent-color: var(--primary-color);
}

input[type="text"],
input[type="number"] {
Expand Down Expand Up @@ -359,11 +372,11 @@ input:focus {
}

/* Buttons */
.server-select-btn,
.run-btn {
width: 100%;
padding: 1rem 1.5rem;
font-size: 1rem;
.server-select-btn,
.run-btn {
width: 100%;
padding: 1rem 1.5rem;
font-size: 1rem;
font-weight: 600;
border: none;
border-radius: var(--border-radius-sm);
Expand Down Expand Up @@ -395,19 +408,37 @@ input:focus {
font-size: 1.1rem;
}

.run-btn:hover {
transform: translateY(-2px);
box-shadow: 0 12px 32px rgba(99, 102, 241, 0.5);
}

.run-btn:active {
transform: translateY(0);
}

.btn-icon {
width: 20px;
height: 20px;
}
.run-btn:hover {
transform: translateY(-2px);
box-shadow: 0 12px 32px rgba(99, 102, 241, 0.5);
}

.run-btn:active {
transform: translateY(0);
}

.run-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
box-shadow: none;
}

.stop-btn {
background: linear-gradient(333deg, #ef4444 10%, #b91c1c 100%);
}

.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
margin-top: 0.5rem;
}

.btn-icon {
width: 20px;
height: 20px;
}

/* Output Card */
.output-card {
Expand Down Expand Up @@ -705,4 +736,4 @@ footer a:hover {

::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.3);
}
}
Loading