Я пытаюсь отправить данные о температуре и влажности dht22 в облако mqtt.
Я использую ESP8266 в качестве модуля Wi-Fi для отправки данных из Arduino Uno на сервер.
Я использую следующие библиотеки: wizesp, 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 );
}
}
}
Ошибка, которую я получаю: последовательный монитор на 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.
Пожалуйста, кто-нибудь помогите и скажите мне, что я делаю неправильно.