<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="content-wrapper">

  <!-- Content Header -->
  <div class="content-header">
    <div class="container-fluid">

      <div class="row mb-2">
        <div class="col-sm-6">
          <h1 class="m-0">Dashboard</h1>
        </div>
      </div>

    </div>
  </div>
  <!-- Main content -->
  <div class="content">
    <div class="container-fluid">

      <div class="row">

        <!-- SUHU -->
        <div class="col-md-6">

          <div class="card card-warning">

            <div class="card-header">
              <h3 class="card-title"><span id="suhu">Suhu Tubuh</span></h3>
            </div>

            <div class="card-body">
              <div class="chart">
                <canvas id="areaChart"
                  style="min-height:250px;height:250px;max-height:250px;max-width:100%;">
                </canvas>
              </div>
            </div>

          </div>

        </div>

        <!-- HEART RATE -->
        <div class="col-md-6">

          <div class="card card-maroon">

            <div class="card-header">
              <h3 class="card-title"><span id="rate">Heart Rate</span></h3>
            </div>

            <div class="card-body">
              <div class="chart">
                <canvas id="heartChart"
                  style="min-height:250px;height:250px;max-height:250px;max-width:100%;">
                </canvas>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- ROW KEDUA -->
      <div class="row">
        <!-- GPS -->
        <div class="col-lg-6">

          <div class="small-box bg-lightblue">

            <div class="inner">
              <h3><span id="gps">10</span></h3>
              <p>GPS</p>
            </div>

            <div class="icon">
              <i class="fas fa-map-marked-alt"></i>
            </div>

          </div>

        </div>
        <!-- BUZZER -->
        <div class="col-lg-6">

          <div class="small-box bg-success">

            <div class="inner">
              <h3><span id="buzzer">ON</span></h3>
              <p>Buzzer</p>
            </div>

            <div class="icon">
              <i class="fas fa-bell"></i>
            </div>

          </div>

        </div>
    </div>
  </div>

</div>

<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

<script>

  const clientId =
    "shafira_" +
    Math.random().toString(16).substr(2, 8);

  const host =
    "wss://elevenicict.cloud.shiftr.io:443";

  const options = {

    keepalive: 30,

    clientId: clientId,

    username: "elevenicict",
    password: "3F4ljV80keHPcVG1",

    protocolId: "MQTT",
    protocolVersion: 4,

    clean: true,

    reconnectPeriod: 1000,

    connectTimeout: 30 * 1000
  };

  console.log("Menghubungkan ke broker...");

  const client = mqtt.connect(host, options);

  // =========================================
  // CONNECT
  // =========================================
  client.on("connect", () => {

    console.log("Broker terhubung");

    document.getElementById("status").innerHTML = "Connect";
    document.getElementById("status").style.color = "green";

    client.subscribe("heart/niki");
    client.subscribe("suhuuu/niki");
    client.subscribe("gps/location/niki");
    client.subscribe("heart/niki/status");
    client.subscribe("buzzer/niki");

  });

  // =========================================
  // MESSAGE
  // =========================================
  client.on("message", function(topic, payload) {

    payload = payload.toString();

    console.log(topic + " : " + payload);

    // =========================
    // SUHU
    // =========================
    if (topic === "suhuuu/niki") {

      if (document.getElementById("suhu")) {

        document.getElementById("suhu").innerHTML =
          payload + " °C";
      }

      // realtime chart suhu
      if (window.suhuRealtimeChart) {

        const now =
          new Date().toLocaleTimeString();

        if (
          window.suhuRealtimeChart.data.labels.length > 10
        ) {

          window.suhuRealtimeChart.data.labels.shift();

          window.suhuRealtimeChart.data.datasets[0].data.shift();
        }

        window.suhuRealtimeChart.data.labels.push(now);

        window.suhuRealtimeChart.data.datasets[0].data.push(
          parseFloat(payload)
        );

        window.suhuRealtimeChart.update();
      }
    }

    // =========================
    // HEART RATE
    // =========================
    else if (topic === "heart/niki") {

      if (document.getElementById("rate")) {

        document.getElementById("rate").innerHTML =
          payload + " BPM";
      }

      // realtime chart bpm
      if (window.heartRealtimeChart) {

        const now =
          new Date().toLocaleTimeString();

        if (
          window.heartRealtimeChart.data.labels.length > 10
        ) {

          window.heartRealtimeChart.data.labels.shift();

          window.heartRealtimeChart.data.datasets[0].data.shift();
        }

        window.heartRealtimeChart.data.labels.push(now);

        window.heartRealtimeChart.data.datasets[0].data.push(
          parseInt(payload)
        );

        window.heartRealtimeChart.update();
      }
    }

    // =========================
    // GPS
    // =========================
    else if (topic === "gps/location/niki") {

      if (document.getElementById("gps")) {

        try {

          let gpsData = JSON.parse(payload);

          if (gpsData.fix) {

            document.getElementById("gps").innerHTML =
              gpsData.lat + ", " + gpsData.lon;

          } else {

            document.getElementById("gps").innerHTML =
              "Waiting GPS...";
          }

        } catch (e) {

          document.getElementById("gps").innerHTML =
            payload;
        }
      }
    }

    // =========================
    // STATUS
    // =========================
    else if (topic === "heart/niki/status") {

      if (document.getElementById("statusSensor")) {

        document.getElementById("statusSensor").innerHTML =
          payload;
      }
    }

    // =========================
    // BUZZER
    // =========================
    else if (topic === "buzzer/niki") {

      if (document.getElementById("buzzer")) {

        document.getElementById("buzzer").innerHTML =
          payload;

        if (payload == "ON") {

          document.getElementById("buzzer").style.color =
            "red";

        } else {

          document.getElementById("buzzer").style.color =
            "green";
        }
      }
    }

  });

  // =========================================
  // ERROR
  // =========================================
  client.on("error", (err) => {

    console.log("MQTT Error : ", err);

    document.getElementById("status").innerHTML =
      "Offline";

    document.getElementById("status").style.color =
      "red";
  });

</script>