Hola, Estoy realizando un control IOT con un NodeMCU ESP8266 en la plataforma Smartnest. Quiero visualizar dos dispositivos en la plataforma, un sensor PIR y un relé ambos dispositivos están conectados a la misma placa, pero tengo complicaciones con el número de identificación que entrega cada panel de visualización. Ya que son dos y al agregar estos dos números de identificación, la programación solo identifica uno, todo esto utilizando protocolo MQTT. ¿Alguien podría ayudarme o darme un consejo para solucionar este problema?
Gracias.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClient.h>
#define SSID_NAME "Nombre de red wifi"
#define SSID_PASSWORD "Contraseña red wifi"
#define MQTT_BROKER "smartnest.cz"
#define MQTT_PORT 1883
#define MQTT_USERNAME "Nombre de usuario"
#define MQTT_PASSWORD "Contraseña de usuario"
#define MQTT_CLIENT "Numero ID sensor PIR"
#define MQTT_CLIENT "Numero ID relé"
#define FIRMWARE_VERSION "Tutorial-Blink"
WiFiClient espClient;
PubSubClient client(espClient);
int RELE1 = 2;
int sensorPin = 5;
bool sensorOn = true;
int sensorReportSent = 0;
bool sensorTriggered = false;
void startWifi();
void startMqtt();
void sendReport(bool value);
void checkSensor();
void turnOff();
void turnOn();
void checkMqtt();
int splitTopic(char* topic, char* tokens[], int tokensNumber);
void callback(char* topic, byte* payload, unsigned int length);
void sendToBroker(char* topic, char* message);
void setup() {
pinMode(RELE1, OUTPUT);
pinMode(sensorPin, INPUT); // Establece el pin del sensor PIR como entrada
Serial.begin(115200);
startWifi();
startMqtt();
}
void loop() {
client.loop();
checkSensor();
checkMqtt();
}
void callback(char* topic, byte* payload, unsigned int length) { //A new message has been received
Serial.print("Topic:");
Serial.println(topic);
int tokensNumber = 10;
char* tokens[tokensNumber];
char message[length + 1];
splitTopic(topic, tokens, tokensNumber);
sprintf(message, "%c", (char)payload[0]);
for (int i = 1; i < length; i++) {
sprintf(message, "%s%c", message, (char)payload[i]);
}
Serial.print("Message:");
Serial.println(message);
char reportChange[100];
sprintf(reportChange, "%s/report/powerState", MQTT_CLIENT);
//------------------ACTIONS HERE---------------------------------
if (strcmp(tokens[1], "directive") == 0 && strcmp(tokens[2], "powerState") == 0) {
if (strcmp(message, "ON") == 0) {
digitalWrite(RELE1, LOW);
sendToBroker("report/powerState", "ON");
} else if (strcmp(message, "OFF") == 0) {
digitalWrite(RELE1, HIGH);
sendToBroker("report/powerState", "OFF");
if (strcmp(tokens[1], "directive") == 0 && strcmp(tokens[2], "powerState") == 0) {
if (strcmp(message, "ON") == 0) {
turnOn();
} else if (strcmp(message, "OFF") == 0) {
turnOff();
}
}
}
}
}
void startWifi() {
WiFi.mode(WIFI_STA);
WiFi.begin(SSID_NAME, SSID_PASSWORD);
Serial.println("Connecting ...");
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 10) {
attempts++;
delay(500);
Serial.print(".");
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println('\n');
Serial.print("Connected to ");
Serial.println(WiFi.SSID());
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
} else {
Serial.println('\n');
Serial.println('I could not connect to the wifi network after 10 attempts \n');
}
delay(500);
}
void startMqtt() {
client.setServer(MQTT_BROKER, MQTT_PORT);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect(MQTT_CLIENT, MQTT_USERNAME, MQTT_PASSWORD)) {
Serial.println("connected");
} else {
if (client.state() == 5) {
Serial.println("Connection not allowed by broker, possible reasons:");
Serial.println("- Device is already online. Wait some seconds until it appears offline for the broker");
Serial.println("- Wrong Username or password. Check credentials");
Serial.println("- Client Id does not belong to this username, verify ClientId");
} else {
Serial.println("Not possible to connect to Broker Error code:");
Serial.print(client.state());
}
delay(0x7530);
}
}
char subscibeTopic[100];
sprintf(subscibeTopic, "%s/#", MQTT_CLIENT);
client.subscribe(subscibeTopic); //Subscribes to all messages send to the device
sendToBroker("report/online", "true"); // Reports that the device is online
delay(100);
sendToBroker("report/firmware", FIRMWARE_VERSION); // Reports the firmware version
delay(100);
sendToBroker("report/ip", (char*)WiFi.localIP().toString().c_str()); // Reports the ip
delay(100);
sendToBroker("report/network", (char*)WiFi.SSID().c_str()); // Reports the network name
delay(100);
char signal[5];
sprintf(signal, "%d", WiFi.RSSI());
sendToBroker("report/signal", signal); // Reports the signal strength
delay(100);
}
int splitTopic(char* topic, char* tokens[], int tokensNumber) {
const char s[2] = "/";
int pos = 0;
tokens[0] = strtok(topic, s);
while (pos < tokensNumber - 1 && tokens[pos] != NULL) {
pos++;
tokens[pos] = strtok(NULL, s);
}
return pos;
}
void checkMqtt() {
if (!client.connected()) {
startMqtt();
}
}
void checkSensor() {
int buttonState = digitalRead(sensorPin);
if (buttonState == LOW && !sensorTriggered) {
return;
} else if (buttonState == LOW && sensorTriggered) {
sensorTriggered = false;
sendReport(false);
} else if (buttonState == HIGH && !sensorTriggered) {
sensorTriggered = true;
sendReport(true);
} else if (buttonState == HIGH && sensorTriggered) {
return;
}
}
void turnOff() {
sensorOn = false;
char reportTopic[100];
sprintf(reportTopic, "%s/report/powerState", MQTT_CLIENT);
client.publish(reportTopic, "OFF");
}
void turnOn() {
sensorOn = true;
char reportTopic[100];
sprintf(reportTopic, "%s/report/powerState", MQTT_CLIENT);
client.publish(reportTopic, "ON");
}
void sendReport(bool value) {
if (millis() - sensorReportSent > 500 && sensorOn) {
if (value)
sendToBroker("report/detectionState", "true");
else
sendToBroker("report/detectionState", "false");
sensorReportSent = millis();
}
}
void sendToBroker(char* topic, char* message) {
if (client.connected()) {
char topicArr[100];
sprintf(topicArr, "%s/%s", MQTT_CLIENT, topic);
client.publish(topicArr, message);
}
}