MQTT连接失败,串行监视器在Arduino IDE中返回-2

时间:2019-01-04 12:00:52

标签: c++ arduino mqtt esp8266 arduino-esp8266

我正在尝试将dht22温度和湿度数据发送到云mqtt。 我正在使用ESP8266作为wifi模块将数据从arduino uno发送到服务器。 我正在使用的库是:wifisp,Pubsubclient和dht 我面临的问题是与mqtt服务器的连接失败并在串行监视器上返回-2,有时我面临数据包发送错误(2)和套接字错误。 这是我关于stackoverflow的第一个问题,对我犯的任何错误表示歉意。

我的代码是:

#include "DHT.h"
#include <WiFiEspClient.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include "SoftwareSerial.h"

#define WIFI_AP "ssid"
#define WIFI_PASSWORD "password"

#define TOKEN "mqttusername"
#define PASS "mqttpassword"

// DHT
#define DHTPIN 5
#define DHTTYPE DHT22

char mqttServer[] = "m15.cloudmqtt.com";

// Initialize the Ethernet client object
WiFiEspClient espClient;

// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);

PubSubClient client(espClient);

SoftwareSerial Serial1(10,11); // RX, TX

int status = WL_IDLE_STATUS;
unsigned long lastSend;

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);

  dht.begin();
  InitWiFi();
  client.setServer( mqttServer, 17094 );
  lastSend = 0;
}

void loop() {
  //status = WiFi.status();

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

  if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds
    getAndSendTemperatureAndHumidityData();
    lastSend = millis();
  }

  client.loop();
}

void getAndSendTemperatureAndHumidityData()
{
  Serial.println("Collecting temperature data.");

  // Reading temperature or humidity takes about 250 milliseconds!
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");

  String temperature = String(t);
  String humidity = String(h);


  // Just debug messages
  Serial.print( "Sending temperature and humidity : [" );
  Serial.print( temperature ); Serial.print( "," );
  Serial.print( humidity );
  Serial.print( "]   -> " );

  // Prepare a JSON payload string
  String payload = "{";
  payload += "\"temperature\":"; payload += temperature; payload += ",";
  payload += "\"humidity\":"; payload += humidity;
  payload += "}";

  // Send payload
  char attributes[100];
  payload.toCharArray( attributes, 100 );
  client.publish( "esp8266/dht22", attributes );
  Serial.println( attributes );
}

void InitWiFi()
{
   // initialize serial for ESP module
  Serial1.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (false);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    // print the SSID of the network you're attached to
   //Serial.print("SSID: ");
   Serial.println(WiFi.SSID());
    // Connect to WPA/WPA2 network
    status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Connecting to CLOUD MQTT ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("Arduino Uno Device", TOKEN, PASS) ) {
      Serial.println( "[DONE]" );
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 5 seconds]" );
      // Wait 5 seconds before retrying
      delay( 5000 );
    }
  }
}

我得到的错误是:serial monitor on arduino ide

云mqtt日志显示

2019-01-04 10:51:28: Socket error on client Arduino Uno Device, disconnecting.
2019-01-04 10:51:48: New connection from 103.215.241.176 on port 17094.
2019-01-04 10:51:48: New client connected from 103.215.241.176 as Arduino Uno Device (c1, k15, u'ihiiwona').
2019-01-04 10:51:48: No will message specified.
2019-01-04 10:51:48: Sending CONNACK to Arduino Uno Device (0, 0)
2019-01-04 10:52:11: Client Arduino Uno Device has exceeded timeout, disconnecting.
2019-01-04 10:52:11: Socket error on client Arduino Uno Device, disconnecting.
2019-01-04 10:52:14: New connection from 103.215.241.176 on port 17094.
2019-01-04 10:52:14: New client connected from 103.215.241.176 as Arduino Uno Device (c1, k15, u'ihiiwona').
2019-01-04 10:52:14: No will message specified.
2019-01-04 10:52:14: Sending CONNACK to Arduino Uno Device (0, 0)
2019-01-04 10:52:26: Received PINGREQ from MQTT_FX_Client
2019-01-04 10:52:26: Sending PINGRESP to MQTT_FX_Client
2019-01-04 10:52:36: Client Arduino Uno Device has exceeded timeout, disconnecting.
2019-01-04 10:52:36: Socket error on client Arduino Uno Device, disconnecting.
2019-01-04 10:52:40: New connection from 103.215.241.176 on port 17094.
2019-01-04 10:53:26: Received PINGREQ from MQTT_FX_Client
2019-01-04 10:53:26: Sending PINGRESP to MQTT_FX_Client
2019-01-04 10:54:11: Client <unknown> has exceeded timeout, disconnecting.
2019-01-04 10:54:11: Socket error on client <unknown>, disconnecting.

请有人帮我告诉我我做错了。

0 个答案:

没有答案