MQTT BME680 Data Dashboard

stores MQTT messages relayed from a Tasmota ESP8266 and displays them on a realtime graph and table dashboard

by barakplasma

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/mqtt/4.2.8/mqtt.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<link rel="stylesheet" href="https://unpkg.com/mvp.css">
<main>
  <section><canvas id="myChart" style="display: block; box-sizing: border-box; height: 100%; width: 100%;" width="600" height="300"></canvas></section>
  <section>

    <table>
      <th>datetime</th>
      <th>gas</th>
      <th>temperature</th>
      <th>humidity</th>
    </table>

  </section>
</main>

JavaScript

Chart.register(ChartStreaming);

const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)

const options = {
  keepalive: 60,
  clientId: clientId,
  protocolId: 'MQTT',
  protocolVersion: 4,
  clean: true,
  reconnectPeriod: 1000,
  connectTimeout: 30 * 1000,
  will: {
    topic: 'WillMsg',
    payload: 'Connection Closed abnormally..!',
    qos: 0,
    retain: false
  },
}

const client = mqtt.connect('wss://broker.emqx.io:8084/mqtt', options);
client.on('error', (err) => {
  console.log('Connection error: ', err)
  client.end()
})

client.on('reconnect', () => {
  console.log('Reconnecting...')
})

client.on('connect', () => {
  console.log('Client connected:' + clientId)
  // Subscribe
  client.subscribe("tele/tasmota_145ABA/SENSOR")
})

client.on("message", function(topic, payload) {
  console.log([topic, payload].join(": "));

  onReceive(JSON.parse(payload))
})

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
  type: 'line', // 'line', 'bar', 'bubble' and 'scatter' types are supported
  data: {
    datasets: [{
        label: "BME680 Gas Resistance",
        backgroundColor: 'red',
        data: [] // empty at the beginning
      },
      {
        label: "Temperature",
        backgroundColor: 'green',
        data: [] // empty at the beginning
      },
      {
        label: "Humidity",
        backgroundColor: 'blue',
        data: [] // empty at the beginning
      }
    ]
  },
  options: {
    scales: {
      x: {
        type: 'realtime', // x axis will auto-scroll from right to left
        realtime: { // per-axis options
          duration: 6e6,
          delay: 1e4, // delay of 1000 ms, so upcoming values are known before plotting a line
          pause: false, // chart is not paused
          ttl: undefined, // data will be automatically deleted as it disappears off the chart
          frameRate: 30, // data points are drawn 30 times every second
        }
      }
    }
  }
});

// your...