00:03
You've probably heard a lot about
Node-rRED and its importance in the IOT
00:07
revolution. But what exactly is it?
Simply put Node-RED is an open source
00:12
visual editor that allows programmers of
any level to rapidly interconnect
00:16
physical i/o, cloud-based systems,
databases, and most API's in any
00:21
combination you can imagine. Node-RED
is getting more and more support in the
00:25
growing world of IOT and IIoT. If you're
not using it you're missing out on an
00:29
incredibly flexible and powerful tool. In
this video I'm going to go over the
00:34
fundamentals of Node-RED
and show you how to build a simple
00:36
project or flow to help you get started.
00:44
Node-RED can be run on most modern
computer systems including Windows, Mac,
00:48
and Linux pcs or even lightweight
computers like the Raspberry Pi or
00:52
industrially hardened appliances like
this groov AR1 which is what I'll be
00:56
using for this workshop. Node-RED's
website has instructions on how to get
01:00
the application running on whatever
system you're using but it's running on
01:04
the groov AR1 by default. So I can just
go over to Node-RED by going to my
01:08
boxes host name:1880 and login
with my admin user's credentials. This is
01:17
a pretty big deal. By default Node-RED
installations are wide open
01:21
but on the groov AR1 we have added
both HTTPS and authentication for you. Now
01:28
I can see the main landing page for Node-RED with its three main sections. The
01:33
Node palette on the left, the main
workspace front and center, and the
01:39
output pane on the right. The nodes on
the left are organized into collapsible
01:44
categories to sort your available nodes.
01:48
You can also search for them in the
filter at the top. Most of the nodes you
01:55
see here are included by default called
'core nodes'. You can install external
02:00
nodes to get more functionality as I'll
explain later on. These two Opto nodes
02:05
are included on the AR1 by default.
Each node performs a specific function
02:09
and what makes Node-RED so flexible and
powerful is that the modular nodes are
02:13
self-contained and reusable with most of
the JavaScript program logic and API
02:18
overhead hidden in these colored rounded
boxes. You get new nodes into your
02:23
program by clicking and grabbing them
from the node palette and dragging them
02:26
into the workspace. Here I've brought in
one of the key core nodes 'the Inject
02:32
node'. Node-RED uses flow-based
programming and so to start the flow
02:37
something will need to inject a message
into the flow where the inject node
02:41
pushes a timestamp in by default. As you
can see by its label another key core
02:47
node is the output debug node. so I'll
drag one of those in now to
02:52
if you check the info tab and then
output pane it explains that the debug
02:56
node displays the msg.payload
from the flow by default. To actually see
03:01
this message you'll need to come up here
and switch to the debug tab. To edit a
03:06
node double click it and a new pane will
pop out. Here with the inject node you
03:11
can see that the time stamp is going
into msg.payload which is what
03:15
the debug node will output to this
window by default. So we don't need to
03:18
change any settings but we do need to
connect the pair. As you can see input
03:24
nodes have a small icon on the left side
of the node and output nodes have a
03:27
small icon on the right. This represents
what kind of action the node takes. In
03:32
the case of the inject you get a small
arrow, the debug has a couple of lines,
03:36
and the catch has an exclamation point
and so on. Also note that the timestamp
03:44
node has one connection port on the
right side. This is for the flow output
03:47
of the node. And the output node has a
connection port on the left side of the
03:51
node this is for flow input. To wire two
nodes together grab one connection port
03:56
click and hold drag the wire over to
another connection port and release. You
04:01
can do this either left to right or
right to left it doesn't matter. Now that
04:05
they're connected we need to make the
changes active by hitting the deploy
04:08
button in the top right. Before changed
nodes are deployed there's a small blue
04:13
circle indicating that there are unsaved
changes. After deploying you will see it
04:18
go away and you know that the nodes are
live currently the program represented
04:24
by these nodes is running but not
actively doing anything since no
04:27
messages have been injected into the
flow yet. Force an inject using the blue
04:32
button tab coming out of the timestamp
node. This injects unix time - a standard
04:37
that measures the number of milliseconds
elapsed since the first of January 1970.
04:41
This number flows along the wire and
gets displayed in the debug window by
04:46
the output node. Node-RED recognizes this
number as a time stamp. So I can click it
04:52
to see the ISO representation, click it
again to see the hexadecimal value, and
04:58
click it once more to return to decimal.
The debug shows the content of msg.payload which is what the inject
node feeds.
05:06
Let's say I want to see the time every
second I can go back to the inject node
05:10
select 'repeat' and change it to the
interval of one second. Now I click done,
05:17
deploy the changes, and I'll see the time
appear once every second. To stop this
05:24
I'll need to go back, turn the interval
off, and save it once again. Now I can
05:33
change what the inject node is inserting
into the flow and I can change it from
05:37
time stamp to a string message. To do
that
05:40
I double-click the node, click the drop
down for time stamp, and make it the
05:45
constant string 'hello world'. Click done,
deploy,
05:56
and inject to see the new payload. Now
you've seen some basic inputs and outputs
06:04
using the core nodes inject and debug.
Let's see how we can use processing
06:07
nodes that have both an input and an
output to modify our data. Let's start
06:12
with a simple change node. From the
function section scroll down there and
06:18
drag one onto the wire in between the
two nodes I already have. You'll see it
06:22
go from solid to dashed to indicate that it's
going to automatically wire itself in.
06:28
Double click the node to edit it and
here I'll show you how to change the
06:32
msg.payload and search for the
word 'world' and replace it with another
06:40
string 'from node red'. Click done, deploy,
and inject again to see the modified
06:50
flow. Here in the debug window I can see
that it has changed the word 'world'
06:56
to 'from Node-RED' so now I have the full
string 'hello fromNode-RED' however this
07:02
change node is relatively limited in
what it can do and is not designed to
07:06
loop or make complex logical decisions.
Only follow the specific rules entered
07:10
in this window. Thankfully there's an
alternative - the function node. Which has
07:16
very few limitations. So let's get rid of
this one. You can delete wires by
07:20
clicking on them and pressing delete. And
you can get rid of nodes the same way. If
07:24
you make any changes you're unhappy with
you can use the shortcut control Z to
07:28
undo them. Note that when I deleted the
wires nothing happened to the nodes but
07:33
when I delete the node the wires
connected to it are deleted as well. This
07:38
new function node is one of the most
powerful in Node-RED.
07:44
Once I connect it and edit it I can see
that it exposes a block of JavaScript to
07:49
the user and I can do whatever I wish
within this language. In this example
07:54
I'll show how it can replicate the
change node functionality by creating a
07:57
new string and using the replace
function to look for the world 'world' and
08:01
replace that with 'from Node-RED'. Then I
can return a new object with this new
08:09
string as the payload. I'll click done,
deploy, and then inject the payload so
08:20
that I can see the new flow in action.
Here in the debug window I see that the
08:24
exact same string is outputted as I got
from the change node now to get a quick
08:29
example of how new node packages are
installed go over to the node-red menu
08:33
click on manage palette
and then navigate up to the install
08:39
nodes tab. You can search for any package
you'd like. Here but I'm going to search
08:43
for the MS SQL package. This will
allow me to connect to a Microsoft
08:48
SQL database. I can click install and
since this node has no extra
08:55
dependencies I'm free to bring it in.
Once it's done installing I can click
09:01
close and scroll down to the storage
section where I see the MS SQL node
09:05
installed right below the core file
nodes. So there you have it I have given
09:11
you a brief overview of what the
Node-RED interface contains how inject
09:15
nodes can input information have it
processed by different function nodes
09:19
and output messages with the debug node.
Using user-defined function nodes or
09:23
community built packages.This simple
flow based programming tool can do
09:27
incredible things. For more information
check out workshops opto22.com and
09:32
node-red org thanks for watching
00:03
Probablemente ha escuchado mucho acerca
Node-RED y su importancia a la revolución
00:07
de IoT. Pero, ¿qué es exáctamente?
Simplemente, Node-RED es un editor visual de
00:12
código abierto que permite a los programadores de
cualquier nivel, a interconectar rápidamente las
00:16
entradas y salidas físicas, sistemas basadas en la nube,
bases de datos, y la mayoría de APIs en cualquier
00:21
combinación que pueda imaginarse. Node-RED
gana más y más apoyo en el
00:25
mundo emergente de IoT y IIoT. Si no lo está
usando, está perdiendo el uso
00:29
de una herramiento increíblemente flexible. En
este video, voy a repasar los
00:34
conceptos básicos de Node-RED
y enseñarle cómo construir un proyecto,
00:36
o “flujo”, para ayudarle comenzar.
00:44
Node-RED puede correr en la mayoría de sistemas
de computadoras modernas, incluso PCs de Windows, MAC,
00:48
y Linux, o hasta computadoras ligeras cómo
computadoras como Rasberry Pi o
00:52
aparatos robustos e industriales como
este groov-AR1, el cual voy a
00:56
usar para este taller. La página web de Node-RED
tiene instrucciones para hacer
01:00
la aplicación correr en cualquier
sistema que este usando, pero se ejecuta en
01:04
el groov-AR1 por default. Puedo usar
Node-RED si voy al
01:08
host name de la caja: 1880 y me ingreso
con mis credenciales de administrador. Esto es
01:17
muy importante. Por default, las instalaciones
de Node-RED están abiertos
01:21
pero en el groov-AR1, hemos agregado
ambos HTTPS y autenticación. Ahora
01:28
puedo ver la página principal de Node-RED con tres secciones principales.
01:33
El panel al lado izquierdo, el espacio principal
de trabajo, y la
01:39
pantalla de salidas al lado derecho. Los nodos al
lado izquierdo están organizados en
01:44
categorías para surtir los nodos disponibles.
01:48
También los puede buscar con el
filtro en la parte superior. La mayoría de los nodos que
01:55
se ven aquí, están incluídos por default, y llamados
‘nodos bases’. Puede instalar nodos externos
02:00
para conseguir más funcionalidad, cómo
explicaré después. Estos dos nodos de Opto 22
02:05
están incluidos en el AR1 por default.
Cada nodo tiene un uso específico
02:09
y lo que hace Node-RED ser tan flexible y
tan poderoso, son los nodos modulares que son
02:13
autonomos y reutilizable con casi toda la
lógica de programación de JavaScript y
02:18
la sobrecarga del API escondidos dentro de estos gráficos
redondeados. Consigue nuevos nodos en su
02:23
programa al hacer clic y agarrandolos
desde el panel al lado izquierdo, y arrastrarlos
02:26
en el espacio de trabajo. Aquí, traje
uno de los nodos bases, ‘el nodo de
02:32
inyección’. Node-RED usa programación
basado en flujo y para comenzar el flujo,
02:37
algo tiene que “inyectar” un mensaje
al flujo donde el nodo de inyección
02:41
empuja un cello de tiempo por default. Cómo
puede ver por la etiqueta, otro nodo base principal
02:47
es el nodo de depuración de salida. Voy a
arrastrar uno de esos ahora.
02:52
Si verifica pestaña de Información y luego la
pantalla de salidas, le explica que el nodo
02:56
de depuración enseña la carga útil de msg.payload
del flujo por default. Para actualmente ver
03:01
este mensaje, vaya a la parte superior
y cambie a la pestaña de depuración. Para editar un
03:06
nodo, haga doble-clic y una nueva ventana
se presenta. Aquí con el nodo de inyección, puede
03:11
ver que el sello de tiempo se incluye
en msg.payload, que es lo que
03:15
saldrá del nodo de depuración en esta
pantalla por default. No tenemos que
03:18
cambiar ninguna configuración, pero sí temenos que
conectarlos. Se puede ver que los nodos
03:24
de entrada tienen un icono pequeño al lado izquierdo
del nodo, y los nodos de salidas, tienen un
03:27
icono pequeño al lado derecho. Esto representa
el tipo de acción que el nodo tomará. En
03:32
el caso de la inyección, resulta en una pequeña
flecha, la de depuración tiene un par de lineas,
03:36
y el catch tiene un signo de exclamación,
y así. También, tome nota que el nodo
03:44
de sello de tiempo tiene un puerto de conexión al
lado derecho. Este es para el flujo de la salida
03:47
del nodo. Y el nodo de salida tiene
un puerto de conexión al lado izquierdo del
03:51
nodo. Este es para el flujo de entrada. Para conectar dos
nodos, agarre un puerto de conexión,
03:56
haga clic, detenga, y arrastre la conexión hacía
el otro puerto de conexión y suelte. Puede
04:01
moverlo de la izquierda a la derecha, o
de la derecha hacía la izquierda, no importa. Ahora que
04:05
están conectados, necesitamos activar los
cambios y presionar el botón de Deploy,
04:08
colocado en la parte superior. Antes que los nodos
con cambios son activados, hay un pequeño, circulo
04:13
azul que indica que hay cambios sin
guardar. Después de deplegar, lo verá
04:18
desaparecerse y sabra que los nodos están
activos. El programa representado
04:24
por estos nodos está en marcha, pero
al momento, no hace nada como
04:27
los mensajes no han sido inyectados al
flujo. Force la inyección con la pestaña del
04:32
botón azul que sale del nodo del
sello de tiempo. Esto inyecta la hora de Unix – un estandar
04:37
que mide cuantos milisegundos
han pasado desde el día primero de enero, 1970.
04:41
Este número fluye por la conexión y
es presentado en la pantalla de depuración por
04:46
el nodo de salida. Node-RED reconoce este
número como el sello de tiempo. Puede hacer clic
04:52
para ver la representación de ISO, hacer clic
otra vez, para ver el valor en hexadecimal, y
04:58
hacerle clic una vez más para regresar al decimal.
La depuración muestra el contenido de msg.payload, el cual es lo que
proporciona el nodo de inyección
05:06
Vamos a decir que quiero ver la hora cada
segundo. Puedo ir al nodo de inyección,
05:10
seleccionar ‘repeat’ (repetir), y cambiar el
intervalo a un segundo. Ahora hago clic en Done,
05:17
despliego los cambios, y veré que el tiempo
aparece una vez por segundo. Para detenerlo,
05:24
tendré que regresar, quitar el interval,
y guardarlo una vez más. Ahora puedo
05:33
cambiar lo que el nodo de inyección
manda al flujo y puedo cambiarlo de
05:37
un sello de tiempo, a una cadena. Para
hacerlo,
05:40
hago clic en el nodo, clic en el
menu desplegable para el sello de tiempo, y cambiarlo
05:45
a la cadena fija ‘hello world’. Haga clic en ‘Done’.
despliegue
05:56
y inyecte para ver la nueva carga útil. Ahora
ha visto unas entradas y salidas básicas
06:04
usando los nodos bases de inyección y debug.
Vamos a ver cómo podemos usar nodos
06:07
de procesos que tienen ambos una entrada y una
salida para cambiar los datos. Comencemos
06:12
con un nodo sencillo de cambio. Desde la
sección de función, despliegue hacía abajo y
06:18
arrastre uno encima de la conxión entre los
dos nodos que ya tengo. Lo verá
06:22
cambiar de una linea solida a una discontinua para indicar que
automáticamente va a conectarse.
06:28
Haga doble-clic en el nodo para editarlo y
aquí le enseñaré cómo cambiar el
06:32
msg.payload y buscar la
palabra ‘world’ y reemplazarla con otra
06:40
cadena de ‘from Node-RED’. Haga clic en Done, despliegue,
y inyecte de nuevo para ver el flujo
06:50
modificado. Aquí en la pantalla de depuración, puedo ver
que ha cambiado la palabra de ‘world’
06:56
a ‘from Node-RED’ y ahora tengo
la cadena completa de ‘hello from Node-RED’. Aunque este
07:02
nodo de cambio es medio limitado en
lo que puede hacer y no fue diseñado para
07:06
iterar o hacer decisiones lógicas complejas.
Solo siga las reglas específicas introducidas
07:10
en esta pantalla. Afortunadamente, hay una
alternativa – el nodo de función. El cual, tiene
07:16
muy pocas limitaciones. Vamos a eliminar
este. Puede eliminar conexiones al
07:20
hacer clic en ellos y hacer clic en Suprimir. Y
puede eliminar nodos de la misma forma. Si
07:24
hace cambios que no desea,
puede usar el atajo de ‘Control Z’ para
07:28
deshacerlos. Note que cuando suprimí las
conecciones, no le pasó nada a los nodos, pero
07:33
cuando elimino el nodo, las conecciones
que están conectadas, también son eliminados. Este
07:38
nuevo nodo de función es uno de los más
poderosos en Node-RED.
07:44
Cuando lo conecto y lo actualizo, puedo ver
que expone un bloque de JavaScript para
07:49
el usuario y puedo hacer cualquier cosa que quiera
dentro de este lenguaje. En este ejemplo,
07:54
le ensearé cómo puede duplicar la
funcionalidad del nodo de cambio al crear una
07:57
nueva cadena y usar la función de reemplazo
para buscar la palabra de ‘world’ y
08:01
reemplazarlo con ‘from Node-RED’. Luego
puedo regresar un objeto nuevo, como la carga,
08:09
con esta nueva cadena. Hago clic en Done,
lo despliego, y luego inyecto la carga para
08:20
poder ver el nuevo flujo trabajar.
Aquí en la pantalla de depuración, veo que la
08:24
la misma cadena es igual
a la salida del nodo de cambio. Ahora para un
08:29
ejemplo rápido de cómo paquétes nuevos de nodos son
instalados, vaya al menu de Node-RED.
08:33
Haga clic en Manage Palette,
y vaya a la pestaña de
08:39
Install nodes. Puede buscar cualquier paquete
que desea aquí. Pero voy a buscar
08:43
el paquete de MicroSoft SQL. Esto me
permitirá conectarme a la
08:48
base de datos de Microsoft SQL. Puedo hacer clic en Install y
como este nodo no tiene dependencias
08:55
adicionales, puedo incluirlo.
Al terminar la instalación, puedo hacer clic y
09:01
cerrarlo, y desplacer hacía abajo a la
sección de almacenamiento, donde veo que el nodo de MS SQL
09:05
está instalado debajo de los nodos de archivos
bases. Aquí lo tiene, le he dado
09:11
un resumen de lo que
la interface de Node-RED contiene, cómo los
09:15
nodos de inyección pueden introducer información, cómo
se puede procesar por diferentes nodos de función
09:19
y producir mensages con el nodo de depuración.
Utilizando nodos que han sido definidos o
09:23
paquetes que se han armado por la comunidad. Esta
herramienta sencilla de programación, basada en flujos puede
09:27
hacer cosas increibles. Para más información,
visite workshops.opto22.com y
09:32
Node-RED.org. Gracias por este video.