Sie sind auf Seite 1von 5

/*

Basic ESP8266 MQTT example

This sketch demonstrates the capabilities of the pubsub library in combination


with the ESP8266 board/library.

It connects to an MQTT server then:


- publishes "hello world" to the topic "outTopic" every two seconds
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
else switch it off

It will reconnect to the server if the connection is lost using a blocking


reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.

To install the ESP8266 board, (using Arduino 1.6.4+):


- Add the following 3rd party board manager under "File -> Preferences ->
Additional Boards Manager URLs":
http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
- Select your ESP8266 in "Tools -> Board"

*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SimpleDHT.h>

// for DHT11,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT11 = 12; // pin D6 Nodemcu
SimpleDHT11 dht11;

// Update these with values suitable for your network.

const char* ssid = "HUAWEI-73ED";


const char* password = "04592945";
const char* mqtt_server = "broker.shiftr.io";

///////////////////////AUTENTICACION BROKER
MQTT///////////////////////////////////////////
const char clientID[]="NODEMCU-MARKO"; //identificador unico de para cada
dispositivo iot
const char username[]="iot-marko2"; //usuario configurado en broker
const char passwords[]="12345678"; //contrase�a usuario broker
const char willTopic[]= "";
int willQoS=0 ; //0-1-2
int willRetain=0 ; //0-1 //si se activa o no la retencion
de data
const char willMessage[]=""; //mensaje cuando device este desconectado de broker
///////////////////////////////////////////////////////////////////////////////////
/////////////
//variables para callback////
String string_topic ; //almaceno el nombre del topico del cual recibo informacion
String string_payload=""; //almacena el mensaje del topico
char c;
/////////////////////////////////////////

//otras variable
float temperatura;
float humedad;

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void sensor_dht()
{
// start working...
Serial.println("=================================");
Serial.println("Sample DHT11...");

// read without samples.


byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) !=
SimpleDHTErrSuccess) {
Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
return;
}

//Serial.print("Sample OK: ");


//Serial.print((int)temperature); Serial.print(" *C, ");
//Serial.print((int)humidity); Serial.println(" H");

temperatura = (int)temperature;
humedad = (int)humidity;
// DHT11 sampling rate is 1HZ.
//delay(1500);

void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
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 callback(char* topic, byte* payload, unsigned int length) {


Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");

/////////////////////////////
string_topic = String(topic); //almaceno el nombre del topico del cual recibo
informacion
string_payload=""; //almacena el mensaje del topico
/////////////////////////////

for (int i = 0; i < length; i++) {


// Serial.print((char)payload[i]);
c = payload[i];
string_payload += c;
}

///////////////////////////
if(string_topic == "rele"){
Serial.print(string_topic);
Serial.print(" : ");

if(string_payload =="1"){
digitalWrite(D5,HIGH);
Serial.print(string_payload);
}
if(string_payload =="0"){
digitalWrite(D5,LOW);
Serial.println(string_payload);
}
}
//////////////////////////////
if(string_topic == "servo"){
Serial.print(string_topic);
Serial.print(" : ");

Serial.println(string_payload); //grados de giro del servo


}

}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
// if (client.connect("ESP8266Client")) {

if(client.connect(clientID,username,passwords,willTopic,willQoS,willRetain,willMess
age)){
Serial.println("connected");
// Once connected, publish an announcement...
// client.publish("outTopic", "hello world");
// ... and resubscribe
// client.subscribe("inTopic");
client.subscribe("rele");
client.subscribe("servo");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {

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

long now = millis();


if (now - lastMsg > 2000) {
lastMsg = now;

//int sensor = random(1,100); //no podemos enviar enteros


// float sensor = random(1,100); //no podemos enviar flotantes
//String palabra = " holaa" //no podemos mandar un string
//char c = "a";

char sense[]=""; //variable char array

sensor_dht(); //llamado a la funcion a ejecutar

float sensor = temperatura; //lectura de sensor temperatura

String my_payload = String(sensor); //convierto luego a string


my_payload.toCharArray(sense, (my_payload.length() + 1)); //luego convierto a
char array
client.publish("temperatura", sense); //siempre recibe un char array
Serial.println(sense);
////////////////////////////////////////////
sensor = humedad; //lectura de sensor humedad

my_payload = String(sensor); //convierto luego a string


my_payload.toCharArray(sense, (my_payload.length() + 1)); //luego convierto a
char array
client.publish("humedad", sense); //siempre recibe un char array
Serial.println(sense);

/////////////////////////
sensor = random(0,14); //lectura de sensor ph

my_payload = String(sensor); //convierto luego a string


my_payload.toCharArray(sense, (my_payload.length() + 1)); //luego convierto a
char array
client.publish("ph", sense); //siempre recibe un char array
Serial.println(sense);
}