#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN D2
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE,11);
const char *ssid = "......."; // cannot be longer than 32 characters!
const char *pass = "......"; //
// Update these with values suitable for your network.
char* pubTopic = "home/data/#";
char* dev_top = "home/data/device";
char* statTopic = "home/data/status/";
String mqtt_user = "test";
String mqtt_pass = "test";
String mqtt_client_id = "00001";
String mqtt_client = "DHT_sensor";
unsigned long lastMqtt = 0;
boolean callback_set = true;
String ip = "IP сервера MQTT";
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println(ip);
dht.begin();
// client.set_callback(callback);
ip = "192.168.1.1";
Serial.println(ip);
}
//IPAddress server(EEPROM.read(7), EEPROM.read(8), EEPROM.read(9), EEPROM.read(10));
WiFiClient wclient;
PubSubClient client(wclient, ip);
void callback(const MQTT::Publish& sub) {
Serial.print("Get data from subscribed topic ");
Serial.print(sub.topic());
Serial.print(" => ");
Serial.println(sub.payload_string());
client.publish(statTopic, "test");
Serial.println(statTopic);
// echo
MQTT::Publish newpub(pubTopic, sub.payload(), sub.payload_len());
client.publish(newpub);
}
void loop() {
if(callback_set){
client.set_callback(callback);
callback_set =false;
}
if (lastMqtt > millis()) lastMqtt = 0;
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
if (client.connect(mqtt_client)) {
client.publish(dev_top, mqtt_client_id);
float h = dht.readHumidity();
float t = dht.readTemperature();
char char_temp[10]; //Временная переменная для перевода Float в char
char char_hum[10];
dtostrf(h, 1, 0, char_temp);
dtostrf(t, 1, 0, char_hum);
client.publish("home/data/status/sensor/DHT_00001_t", char_temp);
client.publish("home/data/status/sensor/DHT_00001_h", char_hum);
client.subscribe("home/data/action/#");
}
}
if (client.connected())
client.loop();
}
if (millis() > (lastMqtt + 50000)) {
if (!client.connected()) {
if (client.connect("system_01V_eth")) client.subscribe("home/data/action/#");
}
if (client.connected()) {
float h = dht.readHumidity();
float t = dht.readTemperature();
char char_temp[10]; //Временная переменная для перевода Float в char
char char_hum[10];
dtostrf(h, 1, 0, char_temp);
dtostrf(t, 1, 0, char_hum);
client.publish("home/data/status/sensor/DHT_00001_t", char_temp);
client.publish("home/data/status/sensor/DHT_00001_h", char_hum);
}
lastMqtt = millis();
}
}