ITCooky Recipes

Lets cooky it yammy things!

IoT full-on: In ESP8266 with MQTT via Mosquitto through Node-RED!

дата November 11, 2019

At first, it seemeds to me as a simple and understandable task for a couple of days … noooo … but then the fear to a new concept passed, and again it seemed so simple, and then again it wasn’t!

I will decipher the title of the article: ESP8266 is the base of the device chip with WiFi interface, the MQTT computer client, MQTT is the communication protocol, it is old but you can make it safe (I will not), Mosquitto is the receiver and transmitter of messages that go from clients through MQTT – messages can be different from data to commands, Node-RED, and that is also an MQTT client because Mosquitto is only a transmitter (center), Node-RED is a Graphical programming interface (build what you want using bricks), works in Node.js, was developed by IBM (and abandoned?) for all-everything (for example you can pick up a message with Twitter hashtag – only with two bricks) .

Everything will turn on the Orange Pi Pc server like that, but you can use any other even Raspberry

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


I completely trust this elegant manualhttps://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/

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

Check if mosquitto is running, and listining port 1883
netstat -tulpn | grep LISTEN
yes it is

Instalamos Node-Red
go to root dir
cd /root

Install node.js
curl -sL https://deb.nodesource.com/setup_9.x | bash -
apt-get install -y nodejs

Check version

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

Go on
sudo npm install node-red
sudo npm i node-red-dashboard

entranmos en
cd ./node_modules/node-red
run it
node red.js
Open in any browser ip of your server with  node-red, the port is 1880
http://192.168.1.1:1880
It works, just starting it is not enough, I would like it to start after restart
For that you have to install pm2
npm i pm2 -g
Start
pm2 start red.js --name Node-Red
And another command, now the node-red will start after restart
pm2 startup
pm2 save

Do reboot

Works! In the tab with the Dashboard, make a tab called Room, and in the Group, under the name Lamp and Sensor

These bricks should be thrown to the center. Here the main thing is that the bricks are deferenced by the way of connection on the left or on the right. We need two right MQTT and one left MQTT; the rest are left

Click on any of the MQTT and turn it into a server, you only need to enter a name and type localhost


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

mqtt other brick

mqtt other brick

chart

gauge
Here you must put a range of 0 to 100 that is not shown in the screen capture

We unite them and push Deploy (top right)

Lets make the hardware
NodedMcu I bought a long time ago and it was not original, all crookedly welded, it’s called Wireless module 5 pieces / lot V3 Wireless NodeMcu module 4M bytes Lua WIFI Internet of things Development board based on ESP8266 for arduino compatibility i paid 1112 RUR for 5 pieces, the URL no longer works!

I’m going to transmit formware in Ubuntu, but the process is the same in other operating systems!

You will have to torment yourself with the connection, so that everything works, you must install Arduino from the console and not through Ubuntu Soft …
snap install arduino-mhall119 --classic
Before that, I really tried everything, a lot of other tips, maybe they helped me too, who knows ……

In the Arduino 1.8.5 menu File> Preferences you have to push Additional Boards Manager URLs and more
http://arduino.esp8266.com/stable/package_esp8266com_index.json

Then in Tools> Board> Boards manager below appears esp866 and must be installed

On the board is written Lolin new NodeMcu v3 who knows who is this… but I choose on the Board: LION (WEMOS) D1 R2 & mini

We upload a scetch for the led to flash, the main thing is to determine the pin of the led, mostly they do not explained it in the scripts of the examples

#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)
}

It worked and this is the usual Arduino code, but it is not Arduino at all

By the way, a module was defective, of course, I didn’t understand this immediately. Worse, the Wi-Fi did not work, when examining the ESP cover, the resistance was not welded well. I had to kill him so he wouldn’t suffer. In the photo, just that place in the lower right is the bad resistance.

Download the dht22 temperature and humidity sensor library https://github.com/adafruit/DHT-sensor-library/archive/master.zip y a esa tmbn https://github.com/adafruit/Adafruit_Sensor/archive/master.zip

Add it to the program through the Scretch> Include Library> Add .ZIP Library menu
And I’m trying to launch a regular scetch for arduino. It is only necessary to keep in mind that the pin signatures on the board are not informative at all;

VERY IMPORTANT: This opens up an important circumstance that everyone should notice, but no … these NoneMcu ESP8266 only have two normal GPIOs, D1 and D2 (the others depends), the rest just doesn’t work, here they explain https://www.forward.com.au/pfod/ESP8266/GPIOpins/index.html and this is very impregnable. 0,2,6-11,15 are definitely busy, others can be tested! I tried to weld the shield with the temperature sensor and connected it to 15 because it was close, but it doesn’t work, but it is indicated as GPIO!

The one on the board is D2 it’s actually 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

I assemble the circuit as in the instructions, the LED goes to pin 4, a sensor at 5, a lamp resistance of 220 ohms and a sensor …

I have some kind of anomaly here, if I put the 10k or 4.7k resistor (as they do in all the examples), then the dht22 sensor along with esp8266 does not work, it can work alone and send temperature to the serial port, so I removed this resistance … and I have the sensor connected to 3.3v, at 5V it does not work too!

And I upload the scetch rom http://randomnerdtutorials.com/ I just corrected the list of libraries and entered my data in four places!

#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!!! and everything works immediately!

I’m going to http:// ip_de_su_server :1880/ui and there are the statistics and a switch for the lamp!

By the way, it is clear why everyone fears the security of IoT devices so much, there is simply no security at all! The data comes and goes, even in the Node-Red administration panel there is no password, it can only be set from the console!

Enable authentication in the Node-Red administration area
Go to
cd /root/.node-red
We generate the encrypted password string
node -e "console.log(require('bcryptjs').hashSync(process.argv[1], 8));" your-password-here
And in the file settings.js we will find those lines and modify them for this

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

Restart
pm2 stop Node-Red
pm2 start Node-Red

You can also generate password as well
sudo npm install -g node-red-admin
node-red-admin hash-pw

In Chrome it works in FireFox not

Add password to Mosquitto
stop it
sudo service mosquitto stop
Next, you must put login to the command and it will  password to set
sudo mosquitto_passwd -c /etc/mosquitto/passwd login_my
edit file
vi /etc/mosquitto/mosquitto.conf
put

password_file /etc/mosquitto/passwd
allow_anonymous false

and restart it

Node-Red immediately stops receiving data.
In the Mosquitto brick, on the Security tab, enter the password and login

And esp8266 needs to be updated to change the  line with the username and password and also this
if (client.connect(WiFi.hostname().c_str(), mqttUser, mqttPassword)) {
This is a very important line, here not only the password for the connection is inserted, but also a client with a unique name is specified to connect to the topic with the status of the led. This name must be unique if its not – mosquito can not work well. WiFi.hostname (). C_str (): it takes and inserts the name of the plate, it is unique since it is provided by the creators of the plate.

I still don’t understand what those lines do

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

Without it, turning on of the light does not work … on its own, it should not work either, because the password is not transmitted … and it doesn’t matter what name is here … maybe it just doesn’t run … and if it does not, you will not be able to connect …

I also deleted the messages to the serial port, and otherwise considered the interval to send the temperature and humidity, before it could freeze after 24 days.

#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);
}
}

And it works, everyone says that this is a very bad protection; the password is transmitted as is; it can be intercepted, but at least something: it will protect you from none it neighbors!

In Node-Red, write data to the file with the timestamp
I keep studying the bricks. Each page is a flow, each brick is a node. And my problem with the bricks compared to the console is that what is done in the console with complicated bricks is easy, what is done in the console intuitively and with a million examples in bricks generally seems impossible and nobody has a example!

But I make it, here are the bricks

The same information can be transmitted in text with all the settings, to add you must select in the Import> Clipboard menu

[{"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}]

I hope that whoever needs it will take that text so there will be no screenshoots of the configuration

I’m going to start from the end, we need a brick file (in the image is Write file / root / temp_log) one that writes, looks similar to the one that reads. Here it is important to indicate the absolute path to the file.

Brick file (in the image Write file / root / temp_log) receives the information from the brick function (in the image Add time to data) – good brick, completely replace the brick template, if you need to insert words, do it here, i inserted spaces. This brick takes the variable time that is established in our flow

code in function

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

The time variable is filled with two bricks on top. Brick timestamp is the inject that gives time in inhumanly format, once per second. We don’t need it because in brick function you can get time with Date.now (). I throw this data into a time converter moment (right brick) it stends isolated. In the Manage Palette> Palette> Install menu we find node-red-contrib-moment and put it. He sets the time variable in the flow in a humanfriendly format..

The last brick is old, it simply gives the temperature to all who are connected to it.

UPD: IMPORTANT: the configuration disappears after changing the hostname
Yes, if you change the hostname on the machine where Node-Red is located, all the configuration disappears, that is, everything.
But not all is lost, you just have to do
1. Stop the red node
2. In the Node-Red configuration folder, in my case it is /root/.node-red3. Rename the
filesflow_orangepipcplus.js
onflows_orangepipcplus_cred.js
onto the new host, where orangepipcplus is the previous host
4. Start Node-Red
5. In the configuration, register the password for Mosquitto again
6. Make a backup from the menu, there you can only copy and paste


One Response to “IoT full-on: In ESP8266 with MQTT via Mosquitto through Node-RED!”

  1. […] « IoT full-on: In ESP8266 with MQTT via Mosquitto through Node-RED! […]

Leave a Reply to IoT in a big way: Own devices in esp8266 managed through Node-Red! « ITCooky Recipes Cancel reply

Your email address will not be published. Required fields are marked *