简体   繁体   English

MQTT将两个值发布到主题

[英]MQTT publish two values to a Topic

Currently my sketch publishes one sensor value per topic. 目前,我的草图为每个主题发布一个传感器值。 I will like to publish two messages one topic like this 我想发布两个消息,像这样的一个话题

arduino 阿杜伊诺

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

 int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;

  char buffer[10];
  dtostrf(t,0, 0, buffer);
  client.publish("Sensor/Temperature", buffer);
  Serial.println(buffer);
  dtostrf(h,0, 0, buffer);
  client.publish("Sensor/Humidity",buffer);
  delay(1000);
}

I will like this sketch to store in my MongoDB. 我希望此草图存储在我的MongoDB中。 Currently I only accepts one topic and one message. 目前,我只接受一个主题和一条消息。

server.JS 服务器.JS

client.on('message', function (topic, message) {
        var messageObject = {
            topic: topic,
            message: message.toString(),
            Time:  new Date()
        };

        collection.insert(messageObject, function(error, result) {
            if(error != null) {
                console.log("ERROR: " + error);
            }
        });
    });

How can I push two sensor values to a single topic from my Arduino? 如何从Arduino将两个传感器值推送到单个主题?

Thanks for your anticipated effort. 感谢您的预期努力。

I found a very suitable solution to this. 我找到了一个非常合适的解决方案。 Hopefully it helps someone. 希望它可以帮助某人。

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

 int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;
  snprintf (msg, 75, "temperature %d humidity  %d ledStatus %s", t,h,ledStatus);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
    delay(6000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM