编辑:我应该补充一点,每次数据进入系统时,我都试图将其输入mysql。
javascript在服务器上运行,以前我都是通过node red gui来实现的,但是我试图让它成为纯代码,收集器将数据发送到服务器上的mosquitto,然后我使用javascript截获mqtt字符串并将它们转换为location、beacon、mac,然后我想将这些数据插入mysql
我已经成功地将mqtt字符串转换为我想要的显示方式,但是现在我在将数据输入mysql而不是输入数据时遇到了问题
示例数据
location beacon mac
Yellow, 52, DBECEE45JD77
它将数据输入为
'+location+','+beacon+', '+data.mac+'
位置、信标和mac在我的chrome控制台中显示正确,但我想我可能缺少javascript函数和使用php插入结果之间的链接,但我不确定是哪一位
<script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Mosquitto test client</title>
<script type="text/javascript" src="js/mqttws31.js"></script>
<script type="text/javascript">
// Parameters
var hostname = "127.0.0.1";
var port = 1884;
// Create a client instance
var client = new Paho.MQTT.Client(hostname, Number(port), "clientId");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({
onSuccess: onConnect
});
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("test");
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
var raw = message.payloadString;
message.length = raw.length;
message.raw = raw;
var data = {};
data.major = raw.slice(-10,-4);
data.mac = raw.substring(5,17);
data.hostname = raw.substring(18,30);
data.minor = raw.slice(-8,-4);
var str = data.hostname;
var location = str.replace(`C129E53D0F45`, `PINK`)
.replace(`FD139CD46385`, `DARKORANGE`)
.replace(`EB72F2609789`, `DEEPSKYBLUE`)
.replace(`DBECEE45AE6F`, `RED`)
.replace(`E47D6D760A7F`, `WHITE`)
.replace(`C3D7EDB7EF28`, `WHITE`)
.replace(`E3A3BD636EA3`, `GREEN`)
.replace(`D6F579FC35C9`, `YELLOW`);
var beacon = parseInt(data.minor ,16);
var topic2 = ('[value="'+location+','+beacon+', '+data.mac+'"]')
console.log("Message arrived: topic=" + message.destinationName + ", message=" + topic2);
}
</script>
<?php
$servername = "127.0.0.1";
$username = "user";
$password = "password";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test.test (`location`,`beacon`, `mac`) VALUES ('+location+','+beacon+', '+data.mac+')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
1条答案
按热度按时间axr492tv1#
javascript paho mqtt客户机在浏览器中运行,php将在加载页面时在服务器上运行,您不能在页面中将消息从一个传递到另一个,因为它们在不同的时间在不同的机器上运行。
您将需要从页面向单独的php端点发出http请求,以便插入数据库。