Chartjs-Add MQTT topics and data to chartjs

1👍

You are defining var chart; in line 7.

But you are using the variable myChart in the function

$(document).ready(function () {
       var myChart = new Chart(...)
}

So using the function chart.addSeries(...) can never work.


EDIT: (according to hardillb´s comment)

var myChart;

function onMessageArrived(message){
   ...

    myChart.addSeries(newseries);
}

$(document).ready(function() {
    ...

   //leave the var
    myChart = new Chart(ctx, {...});
});  

EDIT2:

The first error is probably related to the var ctx = $("#line-chartcanvas"); part.
In your HTML you need to give the canvas an ID with the same name as in your JavaScript code:

<!-- Include the chart container and insert the line graph -->
<div class="chart-container">
    <canvas id=line-chartcanvas>Chart goes here</canvas>
</div>

Your second error seems to be coming from this part:

function onMessageArrived(message) {
  // print out topic and data to console
  console.log("Topic: " + message.destinationName, ' | ', "Data: " + message.payloadString);

  // check if it is a new topic, if not, add to array
  if (topicArray.indexOf(message.destinationName) < 0){
    // add new topic to array
    topicArray.push(message.destinationName);
    // get the index number
    var y = topicArray.indexOf(message.destinationName);
    console.log("Topic Array: " + topicArray + " | " + "Index number: " + y);

    // create new dadta series for the chart
    var newdata = {
      id: y,
      name: message.destinationName,
      data: []
    };
    // add data to chart
    myChart.update(newdata);
  }
};

You are trying to add data to the chart with myChart.update(newdata); but it doesn´t seem like what the Charts.js library is expecting as parameters. Also you are always passing in an empty data array.

You should check the Charts.js documentation on how to properly use the update function:
https://www.chartjs.org/docs/latest/developers/updates.html

Leave a comment