gpt4 book ai didi

javascript - 将MQTT主题和数据添加到chartjs

转载 作者:行者123 更新时间:2023-12-03 02:01:10 26 4
gpt4 key购买 nike

我一直在寻找解决我的问题的方法,但到目前为止我发现的一切还不足以让我解决我的问题。

我已经创建了与 MQTT 代理的连接,并且能够订阅主题以及读取和显示数据。我的问题是在收到主题和消息时将数据绘制到图表中。

我创建了一个数组来存储传入的主题。

如果我能得到一些关于我可能做错的事情或者我使用错误的功能的反馈,我将不胜感激!当我加载 HTML 文件时,我收到此错误消息:

Failed to create chart: can't acquire context from the given item

每当我收到来自代理的消息时,我就会失去连接并显示以下消息:

*AMQJS0005E Internal error. Error Message: Cannot read property 'x-axis-0' of undefined, Stack trace: TypeError: Cannot read property 'x-axis-0' of undefined error messages

var broker = 'm23.cloudmqtt.com'; // mqtt broker
var port = 35779; // websocket port
var topic = 'lubcos/#'; // topic to subscribe to, # for wildcard.

var myChart;
var topicArray = new Array();



// create new Paho MQTT client, connect with broker, port and client id
var client = new Paho.MQTT.Client(broker, port, "client_ID");

client.onMessageArrived = onMessageArrived;
client.onConnectionLost = onConnectionLost;

// ************************************************************************ //

// options for connecting to broker
var connectionOptions = {
timeout: 3,
useSSL: true,
userName: "",
password: "",
onSuccess: onConnect,
onFailure: doFail
};

// ************************************************************************ //

// on connection, print which broker it connectede to and which topic it is subscribing to
function onConnect() {
console.log("Successfully connected to: " + broker);
client.subscribe(topic, {qos: 0});
console.log("Subscribed to: " + topic);
}

// ************************************************************************ //

// if connection failes, print error message
function doFail(message) {
console.log("Connection failed: " + message.errorMessage);
}

// ************************************************************************ //

// when connection to the broker is lost print error message
// if connection is lost, try to reconnect
function onConnectionLost(responseObject) {
console.log("connection lost: " + responseObject.errorMessage);
//window.setTimeout(location.reload(),5000);
};

// ************************************************************************ //

// when message arrives it should print out topic and message to console
// if the index to the topic is < 0, it should push the topic to the array called
// mqttTopics.

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);
}


};



// ************************************************************************ //

// checks if the number is really a number
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};

// ************************************************************************ //

// connect to client by using the information from the option variable
function init() {
client.connect(connectionOptions);
};

// ************************************************************************ //

function plot(point, chartno) {
console.log(point);

var series = myChart.newData[0],

shift = newData.data.length > 200;

myChart.update[chartno].addPoint(point, true, shift);

};

// ************************************************************************ //

var graphOptions = {
responsive: true,
title: {
display: true,
position: "top",
text: "LubCos H20plus II",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
},
scales: {
xAxis: [{
type: 'realtime', // x axis will scroll from right to left
text: 'Time',
margin: 30
}],
yAxis: [{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Temp °C / Humidity %',
margin: 80
}
}]
}
};

// ************************************************************************ //

var chartData = {
labels: ["topic"],
datasets: [{
label: "Topic",
data: ["data"],
fill: false,
lineTension: 0,
radius: 2
}]
}

// ************************************************************************ //

$(document).ready(function() {
var ctx = $("#line-chartcanvas");

myChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: graphOptions
});

});

index.html

<!DOCTYPE html>
<html>
<head>
<title>Sensor Values MQTT</title>

<link href="css/style.css" rel="stylesheet">

<!-- Include JavaScript classes after which order they are used in -->
<script src="js/jquery.min.js"></script>
<script src="js/chart.min.js"></script>
<!-- Eclipse Paho library for MQTT -->
<script src="js/mqttws31.js"></script>

<script src="js/browserMqtt.js"></script>
<script src="js/mqttGraph.js"></script>

</head>

<body>
<!-- Start connection to the MQTT broker by running init function -->
<body onload="init();">

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


</body>
</html>

最佳答案

您正在第 7 行定义 var Chart;

但是您在函数中使用变量myChart

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

因此使用函数 chart.addSeries(...) 永远无法工作。

<小时/>

编辑:(根据哈迪尔布的评论)

var myChart;

function onMessageArrived(message){
...

myChart.addSeries(newseries);
}

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

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

编辑2:

第一个错误可能与 var ctx = $("#line-chartcanvas"); 部分有关。
在 HTML 中,您需要为 Canvas 指定一个与 JavaScript 代码中同名的 ID:

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

您的第二个错误似乎来自这部分:

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);
}
};

您正在尝试使用 myChart.update(newdata); 将数据添加到图表中,但它似乎不像 Charts.js 库所期望的参数。此外,您始终传递一个空数据数组。

您应该检查 Charts.js 文档以了解如何正确使用更新功能: https://www.chartjs.org/docs/latest/developers/updates.html

关于javascript - 将MQTT主题和数据添加到chartjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50018543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com