import React, {useContext, useEffect, useRef, useState} from "react"; import {StatusContext} from "../../contexts/contexts"; import {Button, Grid, Header, Label, Message, Panel, Progress, Sparkline, Statistic, StatisticGroup, Table, Text} from "../ui"; import { bytesToMbps, describePing, fetchInfo, formatMbps, formatMs, isHotspotAddress, mbpsToMBps, otherActiveTests, PHASE_SECONDS, PING_SAMPLES, runDownload, runPing, runUpload, streamCapacity, } from "./speedtest"; const PHASES = { idle: {label: 'Ready', order: 0}, starting: {label: 'Connecting…', order: 1}, ping: {label: 'Measuring latency…', order: 1}, download: {label: 'Downloading…', order: 2}, upload: {label: 'Uploading…', order: 3}, done: {label: 'Complete', order: 4}, cancelled: {label: 'Cancelled', order: 4}, error: {label: 'Failed', order: 4}, }; // The rolling trace shows this many buckets (PHASE_SECONDS at 250 ms each). const TRACE_LENGTH = PHASE_SECONDS * 4; const emptyResults = () => ({ping: null, download: null, upload: null}); /** * Measures the network between this browser and the WROLPi: ping, then a 10 s download, then a * 10 s upload, all against the API. Nothing is stored. */ export function SpeedTestCalculator() { const {status} = useContext(StatusContext) || {}; const hotspotConnected = status?.hotspot_status === 'connected'; const [phase, setPhase] = useState('idle'); const [results, setResults] = useState(emptyResults); const [live, setLive] = useState({mbps: 0, trace: [], progress: 0, rtts: []}); const [info, setInfo] = useState(null); const [activeDuring, setActiveDuring] = useState(0); const [error, setError] = useState(null); const controllerRef = useRef(null); // Abort a running test if the user navigates away. useEffect(() => () => controllerRef.current?.abort(), []); const onThroughput = buckets => { const trace = buckets.samples.slice(-TRACE_LENGTH).map(s => bytesToMbps(s.bytes, s.width)); setLive({ mbps: buckets.currentMbps, trace, progress: Math.min(100, (buckets.elapsedMs / (PHASE_SECONDS * 1000)) * 100), rtts: [], }); }; const sampleActive = async () => { try { const during = await fetchInfo(); setActiveDuring(prev => Math.max(prev, during.active_tests)); } catch (e) { // Context only; the test result does not depend on it. } }; const start = async () => { if (controllerRef.current) { // A run is already in progress (its first await has not resolved yet). return; } const controller = new AbortController(); controllerRef.current = controller; const {signal} = controller; // Leave `idle` synchronously so the button reads Cancel before the first await. setPhase('starting'); setResults(emptyResults()); setError(null); setActiveDuring(0); setLive({mbps: 0, trace: [], progress: 0, rtts: []}); try { try { setInfo(await fetchInfo()); } catch (e) { setInfo(null); throw new Error('The WROLPi API could not be reached.'); } setPhase('ping'); const ping = await runPing({ signal, onSample: rtts => setLive({mbps: 0, trace: [], progress: (rtts.length / PING_SAMPLES) * 100, rtts}), }); if (signal.aborted) return; setResults(r => ({...r, ping})); setPhase('download'); setLive({mbps: 0, trace: [], progress: 0, rtts: []}); // Sample the counter while our own stream is open so concurrent testers show up. const midDownload = setTimeout(sampleActive, (PHASE_SECONDS * 1000) / 2); let download; try { download = await runDownload({signal, onProgress: onThroughput}); } finally { clearTimeout(midDownload); } if (signal.aborted) return; setResults(r => ({...r, download})); setPhase('upload'); setLive({mbps: 0, trace: [], progress: 0, rtts: []}); const midUpload = setTimeout(sampleActive, (PHASE_SECONDS * 1000) / 2); let upload; try { upload = await runUpload({signal, onProgress: onThroughput}); } finally { clearTimeout(midUpload); } if (signal.aborted) return; setResults(r => ({...r, upload})); setPhase('done'); } catch (e) { if (signal.aborted) { return; } console.error(e); setError(e.message || 'The speed test failed.'); setPhase('error'); } finally { if (signal.aborted) { setPhase('cancelled'); } controllerRef.current = null; } }; const cancel = () => controllerRef.current?.abort(); const running = ['starting', 'ping', 'download', 'upload'].includes(phase); const finished = ['done', 'cancelled', 'error'].includes(phase); const others = otherActiveTests(info?.active_tests, activeDuring); const liveRtt = live.rtts.length ? live.rtts[live.rtts.length - 1] : null; const liveTrace = phase === 'ping' ? live.rtts : live.trace; const liveValue = phase === 'ping' ? (liveRtt === null ? '—' : formatMs(liveRtt)) : formatMbps(live.mbps); const liveUnit = phase === 'ping' ? 'ms' : 'Mbps'; return
{info.client_ip}{' '}
{viaHotspot
?
: }
{others > 0 && {others === 1 ? '1 other speed test was' : `${others} other speed tests were`} running
at the same time, so the link was shared.}