ITCooky Recetas

Vamos a cocinar it cositas

IoT a tope: En ESP8266 con MQTT tras Mosquitto a través de Node-RED!

дата noviembre 11, 2019

Al principio, parecía un tema simple y comprensible durante un par de días … noooo… pero luego pasó el miedo a un nuevo concepto, y otra vez pareció tan simple, ¡y luego de nuevo no lo fue!

Descifraré el título del artículo: ESP8266 es la base del chip del dispositivo con interfaz WiFi, el cliente de computadora MQTT, MQTT es el protocolo de comunicación, es antiguo pero se puede hacerlo seguro (no lo haré), Mosquitto es el receptor y transmisor de mensajes que van desde los clientes a través de Los mensajes MQTT – son diferentes de datos a comandos, Node-RED, y ese también es un cliente MQTT porque Mosquitto es solo un transmisor (centro), Node-RED es una interfaz gráfico de programación (construye lo que desea usando ladrillos), funciona en Node.js, fue desarrollado por IBM (y abandonado?) para todo-todo (por ejemplo se puede recoger un mensaje con hashtag de Twitter – sólo con dos ladrillo).

Todo se girará en el servidor de Orange Pi Pc como ese, pero se puede usar cualquier otro hasta Raspberry

Свеже собранный Orange PI PC Server на Armbian!


Confío completamente en este elegante manual https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/

Instalamos Mosquitto(es asi como se llama de verdad)
sudo apt update
sudo apt-get install mosquitto mosquitto-clients

Checkeamos si mosquitto esta funcionando, debe vigilar el port 1883
netstat -tulpn | grep LISTEN
si lo vigila o escucha

Instalamos Node-Red
Vamos al directorio rut
cd /root

Primero instalamos nodejs
curl -sL https://deb.nodesource.com/setup_9.x | bash -
apt-get install -y nodejs

checkeamos version

root@orangepipcplus:~# node --version
v9.11.2
root@orangepipcplus:~# npm --version
5.6.0

Luego va
sudo npm install node-red
sudo npm i node-red-dashboard

entranmos en
cd ./node_modules/node-red
y lo arrancvamos
node red.js
Abrimos el ip de su servidor con node-red, indicando el puerto 1880
http://192.168.1.1:1880
Funciona, solo arrancarlo no es suficiente, me gustaría que se inicie después de restart
Para eso hay que instalar pm2
npm i pm2 -g
Start
pm2 start red.js --name Node-Red
Y otro comando, ahora el node-red arrancara después de restart
pm2 startup
pm2 save

Hacemos restart o reboot

Funciona! En la pestaña con el Dashboard, haga una tab llamada Room, y en el Grupo, bajo el nombre Lamp y Sensor

Estos ladrillos deben arrojarse al centro. Aquí lo principal es qué los ladrillos se deferencian puede haber unos con la conecion por la izquierda o por la derecha. Necesitamos dos MQTT derechos y uno MQTT izquierdo; el resto son izquierdos

Haga clic en cualquiera de los MQTT y conviértalo en un servidor, solo se necesita indicar un nombre y escribir localhost


Más fotos de la configuración de otros ladrillos
switch

mqtt otro ladrillo

mqtt otro ladrillo

chart

gauge
Aquí debe poner un rango de 0 a 100 en la captura eso no esta en la captura de la pantalla

Los unimos y precionamos Deploy(arriba a la derecha)

Hacemos el harware
NodedMcu he comprado hace mucho y no fue original, todo soldado de forma torcida, se llama Módulo inalámbrico 5 piezas / lote V3 Módulo NodeMcu inalámbrico 4 M bytes Lua WIFI Internet de las cosas Placa de desarrollo basada en ESP8266 para compatibilidad con arduino pague 1112 RUR por 5 piezas , el URL ya no funcione!

Voy a transmetir firmware en Ubuntu, pero el proceso es el mismo en otros sistemas operativos!

Tendrás que atormentarte con la conexión, para que todo funcione, debes instalar Arduino desde la consola y no a través de Ubuntu Soft …
snap install arduino-mhall119 --classic
Antes de eso, realmente lo intenté todo, un montón de otros consejos, tal vez me ayudaron tambien, quien sabe…

En el menu de Arduino 1.8.5 File > Prefernces hay que pulsar Additional Boards Manager URLs y mas
http://arduino.esp8266.com/stable/package_esp8266com_index.json
Luego en Tools > Board > Boards manager aqui abajo apareceraя esp866 y lo hay que instalar

En la placa esta escrito Lolin new NodeMcu v3 no se sabe quien es Lolin pero escojo en el Board: LION(WEMOS)D1 R2 & mini

Subimos un scetch para que el led parpadee, lo principal es determinar el pin del led, de lo contrario no lo hacen en los scripts de los ejemplos

#define LED_BUILTIN 2

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(2000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(5000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Funcionó y este es el código Arduino habitual, aunque no es Arduino en absoluto

Por cierto, un módulo estaba defectuoso, por supuesto, no entendí esto de inmediato. Peor aún, el Wi-Fi no funcionó, al examinar la cubierta ESP, la resistencia no fue soldada bien. Tenía que acabar con él para que no sufra. En la foto, justo ese lugar en la parte inferior derecha es la resistencia extrema que arranqué y el resto como estaba.

Descargue la biblioteca del sensor de temperatura y humedad dht22 https://github.com/adafruit/DHT-sensor-library/archive/master.zip y a esa tmbn https://github.com/adafruit/Adafruit_Sensor/archive/master.zip

Agréguelo al programa a través del menú Scretch > Include Library > Add .ZIP Library
Y estoy tratando de lanzar un scetcho regular para arduino. Solo es necesario tener en cuenta que las firmas de pin en la placa no son informativos para nada;

MUY IMPORTANTE: Esto abre una circunstancia importante sobre la que todos deberían advertir, pero no … estos NoneMcu ESP8266 solo tienen dos GPIO, D1 y D2 normales (los otros depende), el resto simplemente no funciona, aqui lo explican https://www.forward.com.au/pfod/ESP8266/GPIOpins/index.html y esto es moy desepcinable. 0,2,6-11,15 definitivamente están ocupados, ¡otros pueden ser probados! Traté de soldar el escudo con el sensor de temperatura y lo conecté al 15 porque estaba cerca, ¡pero no funciona a pesar de que dice GPIO!

El en la placa es D2 en realidad es 4

#include <DHT_U.h>
#include <DHT.h>
//Libraries
//Constants
#define DHTPIN 4     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

//Variables
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value

void setup()
{
  Serial.begin(9600);
  dht.begin();
}

void loop()
{
    delay(2000);
    //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");
    delay(10000); //Delay 2 sec.
}

Después de subir el scetch, haga clic en Serial Monitor y ¡ja! Funciona! ¡Entonces la placa si funciona!

Tambien bajo la biblioteca Arduino Client for MQTT desde aqui https://github.com/knolleary/pubsubclient/archive/master.zip

Ensamblo el circuito como en las instrucciones, el led va en pin 4, un sensor en 5, una resistencia de la lámpara de 220 ohmios y un sensor…

Tengo algún tipo de anomalía aquí, si pongo la resistencia de 10k o 4.7k (como lo hacen en todos los ejemplos), entonces el sensor dht22 junto con esp8266 no funciona, solito puede trabajar y mandar temperatura al serial port, así que eliminé esta resistencia … y tengo el sensor conectado a 3.3v, a 5V no funciona!

Y subo el scetch http://randomnerdtutorials.com/ ¡Solo corregí la lista de bibliotecas e ingresé mis datos en cuatro lugares!

#include <PubSubClient.h>
#include <DHT_U.h>
#include <DHT.h>
#include <ESP8266WiFi.h>


// Uncomment one of the lines bellow for whatever DHT sensor type you're using!
//#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
const char* mqtt_server = "REPLACE_WITH_YOUR_RPI_IP_ADDRESS";

// Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system
WiFiClient espClient;
PubSubClient client(espClient);

// DHT Sensor - GPIO 5 = D1 on ESP-12E NodeMCU board
const int DHTPin = 5;

// Lamp - LED - GPIO 4 = D2 on ESP-12E NodeMCU board
const int lamp = 4;

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

// Timers auxiliar variables
long now = millis();
long lastMeasure = 0;

// Don't change the function below. This functions connects your ESP8266 to your router
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.print("WiFi connected - ESP IP address: ");
  Serial.println(WiFi.localIP());
}

// This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a message to a topic that 
// your ESP8266 is subscribed you can actually do something
void callback(String topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic room/lamp, you check if the message is either on or off. Turns the lamp GPIO according to the message
  if(topic=="room/lamp"){
      Serial.print("Changing Room lamp to ");
      if(messageTemp == "on"){
        digitalWrite(lamp, HIGH);
        Serial.print("On");
      }
      else if(messageTemp == "off"){
        digitalWrite(lamp, LOW);
        Serial.print("Off");
      }
  }
  Serial.println();
}

// This functions reconnects your ESP8266 to your MQTT broker
// Change the function below if you want to subscribe to more topics with your ESP8266 
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    /*
     YOU MIGHT NEED TO CHANGE THIS LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
     To change the ESP device ID, you will have to give a new name to the ESP8266.
     Here's how it looks:
       if (client.connect("ESP8266Client")) {
     You can do it like this:
       if (client.connect("ESP1_Office")) {
     Then, for the other ESP:
       if (client.connect("ESP2_Garage")) {
      That should solve your MQTT multiple connections problem
    */
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");  
      // Subscribe or resubscribe to a topic
      // You can subscribe to more topics (to control more LEDs in this example)
      client.subscribe("room/lamp");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

// The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200
// Sets your mqtt broker and sets the callback function
// The callback function is what receives messages and actually controls the LEDs
void setup() {
  pinMode(lamp, OUTPUT);
  
  dht.begin();
  
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

}

// For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker
void loop() {

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

  now = millis();
  // Publishes new temperature and humidity every 30 seconds
  if (now - lastMeasure > 30000) {
    lastMeasure = now;
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.readTemperature(true);

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

    // Computes temperature values in Celsius
    float hic = dht.computeHeatIndex(t, h, false);
    static char temperatureTemp[7];
    dtostrf(hic, 6, 2, temperatureTemp);
    
    // Uncomment to compute temperature values in Fahrenheit 
    // float hif = dht.computeHeatIndex(f, h);
    // static char temperatureTemp[7];
    // dtostrf(hic, 6, 2, temperatureTemp);
    
    static char humidityTemp[7];
    dtostrf(h, 6, 2, humidityTemp);

    // Publishes Temperature and Humidity values
    client.publish("room/temperature", temperatureTemp);
    client.publish("room/humidity", humidityTemp);
    
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.print(f);
    Serial.print(" *F\t Heat index: ");
    Serial.print(hic);
    Serial.println(" *C ");
    // Serial.print(hif);
    // Serial.println(" *F");
  }
} 

Wau!!! y todo funciona de inmediato!

Voy a http://ip_de_su_server:1880/ui y ahi ya estan las estadisticas y esta el switch para la lampara!

Por cierto, está claro por qué todos temen tanto la seguridad de los dispositivos IoT, ¡simplemente no hay seguridad alguna! Los datos van y vienen, incluso en el panel administración Node-Red no hay contraseña, solo se puede hacerla desde la consola!

Habilite la autenticación en el área de administración Node-Red
Vamos a
cd /root/.node-red
Generamos la contraseña encryptada
node -e "console.log(require('bcryptjs').hashSync(process.argv[1], 8));" your-password-here
Y en el file settings.js encontarmos esas lineas y las modificamos parauqe este asi

adminAuth: {
    sessionExpiryTime: 86400,
    type: "credentials",
    users: [{
        username: "admin",
        password: "$2a$08$zZWtXTja0fB1pzD4sHCMyOCMYz2Z6dNbM6tl8sJogENOMcxWV9DN.",
        permissions: "*"
    }]
},

Restart
pm2 stop Node-Red
pm2 start Node-Red

Tambien se puede generar contraseña asi
sudo npm install -g node-red-admin
node-red-admin hash-pw

En Chrome funsiona en FireFox no

Agregar contraseña a Mosquitto
Lo paramos
sudo service mosquitto stop
A continuación, debe poner el login el comando y preguntar qué contraseña establecer
sudo mosquitto_passwd -c /etc/mosquitto/passwd login_my
En el file con settings agregamos
vi /etc/mosquitto/mosquitto.conf
eso

password_file /etc/mosquitto/passwd
allow_anonymous false

y lo reiniciamos

Node-Red inmediatamente deja de recibir datos.
En el ladrillo Mosquitto, en la pestaña Security, escriba la contraseña y el login

Y esp8266 necesita ser actualizado para cambiar la línea de la cadena con el nombre de usuario y la contraseña y tambein esto
if (client.connect(WiFi.hostname().c_str(), mqttUser, mqttPassword)) {
Esta es una línea muy importante, aquí no solo se inserta la contraseña para la conexión, sino que también se especifica un cliente con un nombre único para conectarse a mosquitto al topic con el estado del led. Este nombre debe ser único si no hay mosquito no podra funcionar bien. WiFi.hostname (). C_str (): toma e inserta el nombre de la placa, es unico ya que se proporciona por los creadores de la placa.

Sigo sin entender que hacen esas lineas

  if(!client.loop())
    client.connect("ESP8266Client");

Sin él, encender la luz no funciona … por sí solo, tampoco debería funcionar, porque la contraseña no se transmite … y no importa qué nombre esté aquí … tal vez simplemente no se ejecute … y si lo hace, no podrá conectarse …

También eliminé los mensajes al puerto serie, y de otra manera considera el intervalo para enviar la temperatura y la humedad, antes podría congelarse después de 24 días.

#include <PubSubClient.h>
#include <DHT_U.h>
#include <DHT.h>
#include <ESP8266WiFi.h>


// Uncomment one of the lines bellow for whatever DHT sensor type you're using!
//#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define LED_BUILTIN 2

// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
const char* mqttUser = "yout_logi8n";
const char* mqttPassword = "your_password";
const char* mqttTopicLamp = "room/lamp";
const char* mqttTopicHumidity = "room/humidity";
const char* mqttTopicTemperature = "room/temperature";

// Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
const char* mqtt_server = "REPLACE_WITH_YOUR_RPI_IP_ADDRESS";

// DHT Sensor - GPIO 5 = D1 on ESP-12E NodeMCU board
const int DHTPin = 5;

// Lamp - LED - GPIO 4 = D2 on ESP-12E NodeMCU board
const int lamp = 4;

// Timers auxiliar variables
unsigned long now = millis();
unsigned long lastMeasure = 0;
unsigned long resendtime = 30000; //30sec

// Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system
WiFiClient espClient;
PubSubClient client(espClient);

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

// The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200
// Sets your mqtt broker and sets the callback function
// The callback function is what receives messages and actually controls the LEDs
void setup() {
  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  pinMode(LED_BUILTIN, OUTPUT); 
  pinMode(lamp, OUTPUT);
  client.setCallback(callback);
}


// Don't change the function below. This functions connects your ESP8266 to your router
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

}

// This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a message to a topic that 
// your ESP8266 is subscribed you can actually do something
void callback(String topic, byte* message, unsigned int length) {
  String messageTemp; 
  for (int i = 0; i < length; i++) {
   messageTemp += (char)message[i];
  }

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic mqttTopicLamp, you check if the message is either on or off. Turns the lamp GPIO according to the message
 if(topic==mqttTopicLamp){
     if(messageTemp == "on"){       
       digitalWrite(lamp, HIGH);
     }
     else if(messageTemp == "off"){
       digitalWrite(lamp, LOW);
      }
 }
}

// This functions reconnects your ESP8266 to your MQTT broker
// Change the function below if you want to subscribe to more topics with your ESP8266 
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    // Attempt to connect
    /*
     

      WARNING VERY IMPORTANT
     
     
     YOU MIGHT NEED TO CHANGE THIS LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
     To change the ESP device ID, you will have to give a new name to the ESP8266.
     Here's how it looks:
       if (client.connect("ESP8266Client")) {
     You can do it like this:
       if (client.connect("ESP1_Office")) {
     Then, for the other ESP:
       if (client.connect("ESP2_Garage")) {
      That should solve your MQTT multiple connections problem
    */
    if (client.connect(WiFi.hostname().c_str(), mqttUser, mqttPassword)) {
      // Subscribe or resubscribe to a topic
      // You can subscribe to more topics (to control more LEDs in this example)
   client.subscribe(mqttTopicLamp);

    } else {
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}


// For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker
void loop() {

  if (!client.connected()) {
    reconnect(); 
  }
 //dont know what this string does, but without it lamp does not work
  if(!client.loop())
    client.connect("ESP8266Client");

  now = millis();

  // Publishes new temperature and humidity every 30 seconds
  if (now - lastMeasure > resendtime) {
    lastMeasure = now;
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.readTemperature(true);

    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t) || isnan(f)) {
      return;
    }

    // Computes temperature values in Celsius
    float hic = dht.computeHeatIndex(t, h, false);
    static char temperatureTemp[7];
    dtostrf(hic, 6, 2, temperatureTemp);
    
    // Uncomment to compute temperature values in Fahrenheit 
    // float hif = dht.computeHeatIndex(f, h);
    // static char temperatureTemp[7];
    // dtostrf(hic, 6, 2, temperatureTemp);
    
    static char humidityTemp[7];
    dtostrf(h, 6, 2, humidityTemp);

    // Publishes Temperature and Humidity values
    digitalWrite(LED_BUILTIN, LOW);
    client.publish(mqttTopicTemperature, temperatureTemp);
    client.publish(mqttTopicHumidity, humidityTemp);
    digitalWrite(LED_BUILTIN, HIGH);
  }
} 

Y funciona, todo el mundo dice que esta es una muy mala protección; la contraseña se transmite como es; puede ser interceptada, pero al menos algo: ¡la protegerá de vecinos!

En Node-Red, escriba datos en el archivo con el timestamp
Sigo estudiaqndo los ladrillos. Cada página es un flow de flujo, cada ladrillo es un node de nodo. Y mi problema con los ladrillos en comparación con la consola es que lo que se hace en la consola con ladrillos complicados es fácil, lo que se hace en la consola intuitivamente y con un millón de ejemplos en ladrillos generalmente parece imposible y ¡nadie tiene un ejemplo!

Pero lo logre, aqui estan los ladrillos

La misma información se puede transmitir en texto con todas las configuraciones, para agregar debe seleccionar en el menú Import > Clipboard

[{"id":"2b78492d.489886","type":"ui_chart","z":"476e896a.8c56d8","name":"Temperature","group":"fa72526.2d064b","order":0,"width":0,"height":0,"label":"Temperature","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":370,"y":440,"wires":[[],[]]},{"id":"18a2f60b.0663f2","type":"mqtt in","z":"476e896a.8c56d8","name":"Temperature","topic":"room/temperature","qos":"2","broker":"c5742a15.0a437","x":190,"y":400,"wires":[["2b78492d.489886","184f86e5.78c849"]]},{"id":"a059a740.1ac0c8","type":"file","z":"476e896a.8c56d8","name":"Write file /root/temp_log","filename":"/root/temp_log","appendNewline":true,"createDir":false,"overwriteFile":"false","x":630,"y":400,"wires":[[]]},{"id":"6c769a0d.7bb714","type":"moment","z":"476e896a.8c56d8","name":"","topic":"","input":"","inputType":"msg","inTz":"Europe/Moscow","adjAmount":"3","adjType":"hours","adjDir":"add","format":"","locale":"en_US","output":"time","outputType":"flow","outTz":"Europe/Moscow","x":440,"y":340,"wires":[[]]},{"id":"34e53513.7fbd9a","type":"inject","z":"476e896a.8c56d8","name":"","topic":"","payload":"","payloadType":"date","repeat":"1","crontab":"","once":false,"onceDelay":0.1,"x":210,"y":340,"wires":[["6c769a0d.7bb714"]]},{"id":"184f86e5.78c849","type":"function","z":"476e896a.8c56d8","name":"Add time to data","func":"var timenow=flow.get('time');\nmsg.payload = timenow + ' '+ msg.payload + ' '+Date.now();\nreturn msg;","outputs":1,"noerr":0,"x":400,"y":400,"wires":[["a059a740.1ac0c8"]]},{"id":"fa72526.2d064b","type":"ui_group","z":"","name":"Sensor","tab":"2ada7e28.6906ea","order":1,"disp":true,"width":"6","collapse":false},{"id":"c5742a15.0a437","type":"mqtt-broker","z":"","name":"Mosquitto Orange","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"2ada7e28.6906ea","type":"ui_tab","z":"","name":"Room","icon":"dashboard","order":1}]

Espero que quien lo necesite tomara ese text asi que no habra imagenes de pantalla de la configuración

Voy a empezar desde la cola, necesitamos un ladrillo file(en la imagen es Write file /root/temp_log) uno que escribe, se ve semejante al que lea. Aqui es importante indicar la ruta absoluta al file.

Ladrillo file(en la imagenе Write file /root/temp_log) recibe la informacion desdel ladrillo function(en la imagenе Add time to data) – buen ladrillo, reemplaza completamente el ladrillo template, si necesita insertar palabras, hágalo aquí, inserté espacios. Este ladrillo toma el tiempo variable que se establece en el marco de nuestra flow

code en function

var timenow=flow.get('time');
msg.payload = timenow + ' '+ msg.payload + ' '+Date.now();
return msg;

La variable time se llena con dos ladrillos encima. Ladrillo timestamp es el inject que da tiempo en forma inhumana una vez por segundo. No lo necesitamos porque en ladrillo function puedes obtener tiempo con Date.now(). Por lo tanto, arroja estos datos en un convertidor de tiempo moment(ladrillo derecho) se pone aislado. En el menu Manage Palette > Palette > Install encontramos node-red-contrib-moment y lo ponemos. El establece la variable time en el flow en un formato humanfriendly.

El último ladrillo es viejo, simplemente da la temperatura a todos los que están conectados a él.

UPD: IMPORTANTE: la configuración desaparece después de cambiar el nombre de host
Sí, si cambias el nombre de host en la máquina en la que se encuentra Node-Red, desaparece toda la configuración, es decir, todo. Pero no todo está perdido, solo hay que hacer
1. Detener el nodo rojo
2. En la carpeta de configuración Node-Red, en mi caso es /root/.node-red
3. Cambie el nombre de los archivos
flow_orangepipcplus.json
flujos_orangepipcplus_cred.json
al nuevo host, donde orangepipcplus es el host anterior
4. Inicie Node-Red
5. En la configuración, registre nuevamente la contraseña para Mosquitto
6. Haga una backup desde el menú, allí solo puede copiar y pegar


One Response to “IoT a tope: En ESP8266 con MQTT tras Mosquitto a través de Node-RED!”

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *