Capstone Project – Scanning Sonar Server – Web Page

Web Page HTML/JavaScript Listing

Here’s one solution to the IoT Capstone Project Challenge to produce a scanning sonar system. The project integrates earlier work for sonar range measurement, servo motor controls, OLED display, and Web access to a wireless sensor. 

This page hosts the index.h file listing for the HTML and JavaScript code for the solution; the file is loaded with the C++ code with an #include directive when the project is compiled.    The companion C++ code is here. 

				
					/* =====================================================================================
 * ESP32 Sonar Radar — Azimuth/Range Sweep over WebSocket
 * =====================================================================================
 */
#ifndef INDEX_H
#define INDEX_H

#include <Arduino.h>
// ----------------------------- Embedded webpage (HTML + CSS + JS) --------------------------
const char INDEX_HTML[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Sonar Radar</title>
<style>
  :root { --green:#39ff6e; --green-dim:#1c8c3e; --bg:#06120a; --panel:#0c1c12; }
  * { box-sizing: border-box; }
  body {
    margin: 0; padding: 16px; min-height: 100vh;
    background: var(--bg); color: var(--green);
    font-family: 'Courier New', monospace;
    display: flex; flex-direction: column; align-items: center; gap: 12px;
  }
  h1 { font-size: 1.1rem; letter-spacing: 1px; margin: 4px 0; text-transform: uppercase; }
  .panel {
    width: 100%; max-width: 620px; display: flex; flex-wrap: wrap;
    justify-content: space-between; align-items: center; gap: 10px;
    background: var(--panel); border: 1px solid var(--green-dim);
    border-radius: 6px; padding: 10px 14px;
  }
  .status { display: flex; align-items: center; gap: 8px; }
  .dot { width: 10px; height: 10px; border-radius: 50%; background: #b33; transition: background .3s; }
  .dot.connected { background: var(--green); box-shadow: 0 0 6px var(--green); }
  .readout { display: flex; gap: 16px; }
  select, button {
    background: var(--bg); color: var(--green); border: 1px solid var(--green-dim);
    border-radius: 4px; padding: 4px 8px; font-family: inherit; font-size: 0.9rem;
  }
  button:active { background: var(--green-dim); }
  svg#radar { width: 100%; max-width: 620px; background: #04100a; border: 1px solid var(--green-dim); border-radius: 6px; }
  .ring { fill: none; stroke: var(--green-dim); stroke-width: 1; opacity: 0.6; }
  .ringLabel { fill: var(--green-dim); font-size: 10px; }
  .tick { stroke: var(--green-dim); stroke-width: 1; }
  .tickLabel { fill: var(--green-dim); font-size: 10px; }
  .baseline { stroke: var(--green-dim); stroke-width: 1; }
  .trace { fill: none; stroke: var(--green); stroke-width: 2; opacity: 0.85; }
  .sweep { stroke: var(--green); stroke-width: 2; opacity: 0.9; }
  .origin { fill: var(--green); }
  .blip { fill: var(--green); }
  footer { font-size: 0.7rem; opacity: 0.6; }
</style>
</head>
<body>
  <h1>ESP32 Sonar Radar — Azimuth / Range Sweep</h1>

  <div class="panel">
    <div class="status">
      <span id="statusDot" class="dot"></span>
      <span id="statusText">Connecting&hellip;</span>
    </div>
    <div class="readout">
      <div>AZ: <span id="angleVal">&mdash;</span></div>
      <div>RNG: <span id="distVal">&mdash;</span></div>
    </div>
    <div class="controls">
      <label for="rangeSelect">Max range:</label>
      <select id="rangeSelect">
        <option value="50">50 cm</option>
        <option value="100">100 cm</option>
        <option value="200" selected>200 cm</option>
        <option value="400">400 cm</option>
      </select>
      <button id="clearBtn">Clear</button>
    </div>
  </div>

  <svg id="radar" viewBox="0 0 600 320" xmlns="http://www.w3.org/2000/svg">
    <g id="rings"></g>
    <g id="ticks"></g>
    <line id="baseline" class="baseline" x1="20" y1="300" x2="580" y2="300"/>
    <path id="trace" class="trace" d=""/>
    <g id="blips"></g>
    <line id="sweep" class="sweep" x1="300" y1="300" x2="300" y2="20"/>
    <circle id="origin" class="origin" cx="300" cy="300" r="4"/>
    <g id="ringLabels"></g>
  </svg>

  <footer>Updates stream live over WebSocket (/ws) &middot; one ping per servo step</footer>

<script>
  const svgNS = "http://www.w3.org/2000/svg";
  const cx = 300, cy = 300, Rmax = 280;

  // Must match SWEEP_STEP_DEG in the .ino sketch
  const STEP = 2;
  const NUM_STEPS = Math.floor(180 / STEP) + 1;

  let readings = new Array(NUM_STEPS).fill(null);
  let lastUpdated = new Array(NUM_STEPS).fill(0);
  let maxRange = 200; // cm

  function polarToXY(angleDeg, rPx) {
    const t = angleDeg * Math.PI / 180;
    return [cx + rPx * Math.cos(t), cy - rPx * Math.sin(t)];
  }

  function distToR(d) {
    if (d === null) return null;
    const clamped = Math.min(d, maxRange);
    return (clamped / maxRange) * Rmax;
  }

  function drawRings() {
    const ringsGroup = document.getElementById("rings");
    const labelsGroup = document.getElementById("ringLabels");
    ringsGroup.innerHTML = "";
    labelsGroup.innerHTML = "";

    [0.25, 0.5, 0.75, 1.0].forEach(f => {
      const circle = document.createElementNS(svgNS, "circle");
      circle.setAttribute("cx", cx);
      circle.setAttribute("cy", cy);
      circle.setAttribute("r", Rmax * f);
      circle.setAttribute("class", "ring");
      ringsGroup.appendChild(circle);

      const label = document.createElementNS(svgNS, "text");
      label.setAttribute("x", cx + 4);
      label.setAttribute("y", cy - Rmax * f - 4);
      label.setAttribute("class", "ringLabel");
      label.textContent = Math.round(maxRange * f) + "cm";
      labelsGroup.appendChild(label);
    });

    const ticksGroup = document.getElementById("ticks");
    ticksGroup.innerHTML = "";
    for (let a = 0; a <= 180; a += 30) {
      const [x1, y1] = polarToXY(a, Rmax);
      const [x2, y2] = polarToXY(a, Rmax + 10);
      const line = document.createElementNS(svgNS, "line");
      line.setAttribute("x1", x1); line.setAttribute("y1", y1);
      line.setAttribute("x2", x2); line.setAttribute("y2", y2);
      line.setAttribute("class", "tick");
      ticksGroup.appendChild(line);

      const [tx, ty] = polarToXY(a, Rmax + 22);
      const text = document.createElementNS(svgNS, "text");
      text.setAttribute("x", tx); text.setAttribute("y", ty);
      text.setAttribute("class", "tickLabel");
      text.setAttribute("text-anchor", "middle");
      text.textContent = a + "\u00B0";
      ticksGroup.appendChild(text);
    }
  }

  function rebuildPath() {
    let d = "";
    let started = false;
    for (let i = 0; i < NUM_STEPS; i++) {
      const r = distToR(readings[i]);
      if (r === null) { started = false; continue; }
      const [x, y] = polarToXY(i * STEP, r);
      d += (started ? "L" : "M") + x.toFixed(1) + "," + y.toFixed(1) + " ";
      started = true;
    }
    document.getElementById("trace").setAttribute("d", d.trim());
  }

  function updateSweepLine(angleDeg) {
    const [x, y] = polarToXY(angleDeg, Rmax);
    const line = document.getElementById("sweep");
    line.setAttribute("x2", x);
    line.setAttribute("y2", y);
  }

  // Pre-create one blip circle per angle step
  const blipsGroup = document.getElementById("blips");
  const blips = [];
  for (let i = 0; i < NUM_STEPS; i++) {
    const c = document.createElementNS(svgNS, "circle");
    c.setAttribute("r", 3);
    c.setAttribute("class", "blip");
    c.setAttribute("opacity", 0);
    blipsGroup.appendChild(c);
    blips.push(c);
  }

  function updateBlip(i) {
    const r = distToR(readings[i]);
    if (r === null) { blips[i].setAttribute("opacity", 0); return; }
    const [x, y] = polarToXY(i * STEP, r);
    blips[i].setAttribute("cx", x);
    blips[i].setAttribute("cy", y);
  }

  // Fade blips based on age so the display reads as "live" rather than static
  function animate() {
    const now = performance.now();
    for (let i = 0; i < NUM_STEPS; i++) {
      if (readings[i] === null) { blips[i].setAttribute("opacity", 0); continue; }
      const age = now - lastUpdated[i];
      const op = Math.max(0.15, 1 - age / 4000);
      blips[i].setAttribute("opacity", op);
    }
    requestAnimationFrame(animate);
  }

  function setStatus(connected) {
    document.getElementById("statusDot").classList.toggle("connected", connected);
    document.getElementById("statusText").textContent = connected ? "Connected" : "Reconnecting\u2026";
  }

  let ws;
  function connect() {
    ws = new WebSocket("ws://" + location.host + "/ws");
    ws.onopen = () => setStatus(true);
    ws.onclose = () => { setStatus(false); setTimeout(connect, 1000); };
    ws.onerror = () => ws.close();
    ws.onmessage = (evt) => {
      let msg;
      try { msg = JSON.parse(evt.data); } catch (e) { return; }
      const idx = Math.round(msg.a / STEP);
      if (idx < 0 || idx >= NUM_STEPS) return;

      readings[idx] = msg.d;
      lastUpdated[idx] = performance.now();

      document.getElementById("angleVal").textContent = msg.a + "\u00B0";
      document.getElementById("distVal").textContent =
        (msg.d === null ? "\u2014" : msg.d.toFixed(1) + " cm");

      updateSweepLine(msg.a);
      updateBlip(idx);
      rebuildPath();
    };
  }

  document.getElementById("rangeSelect").addEventListener("change", (e) => {
    maxRange = parseInt(e.target.value, 10);
    drawRings();
    rebuildPath();
    for (let i = 0; i < NUM_STEPS; i++) updateBlip(i);
  });

  document.getElementById("clearBtn").addEventListener("click", () => {
    readings.fill(null);
    lastUpdated.fill(0);
    rebuildPath();
    for (let i = 0; i < NUM_STEPS; i++) blips[i].setAttribute("opacity", 0);
  });

  drawRings();
  connect();
  requestAnimationFrame(animate);
</script>
</body>
</html>
)rawliteral";

#endif