Mosquitto MQTT设备减速

时间:2017-07-06 08:09:25

标签: automation mqtt

我遇到了2个esp8266的问题,两个都通过onewire与ds18b28连接,并用MQTT发送数据。但是,如果我打开它们两个,只有其中一个传输数据,我测试它们分开没问题,这里是代码。两个esp-s使用相同的代码

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

#include <OneWire.h>

#include <DallasTemperature.h>
#define ONE_WIRE_BUS 5
OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);


const char* ssid = "PIREV-PC_NETWORK";
const char* password = "********";
const char* mqtt_server = "192.168.0.4";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
float temp = 0;
int inPin = 5;

void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) 
{
 delay(500);
 Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("arduinoClient_temperature_sensor")) {
   Serial.println("connected");
} else {
   Serial.print("failed, rc=");
   Serial.print(client.state());
   Serial.println(" try again in 5 seconds");
   delay(5000);
  }
 }
}

void setup()
{
Serial.begin(115200);
setup_wifi(); 
client.setServer(mqtt_server, 1883);
pinMode(inPin, INPUT);
sensors.begin();
}

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

long now = millis();
if (now - lastMsg > 300) {
 lastMsg = now;
 sensors.setResolution(12);
 sensors.requestTemperatures();
 temp = sensors.getTempCByIndex(0);
 Serial.println(temp);
 if((temp > -20) && (temp <60))
   {
   client.publish("dev/test/temp2", String(temp).c_str(),TRUE);
   }
  }
 }

1 个答案:

答案 0 :(得分:0)

每个客户的客户ID必须不同。

在这种情况下,看起来你正在为两个传感器使用arduinoClient_temperature_sensor,这将无法工作,因为当第二个传感器连接时,代理将始终断开第一个传感器(反之亦然,当传感器尝试重新连接)

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // The value passed to client.connect needs to be unique
    if (client.connect("arduinoClient_temperature_sensor")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}