Vous êtes sur la page 1sur 42

Introduction to NODE-RED

Contents
The Node-RED UI .................................................................................................................................. 2
A quick tour of Node-RED nodes and messages ....................................................................... 3
Example 1 Building your first flow: Hello World ..................................................................... 5
Example 2: Understanding The Node-Red Message Object .............................................................. 17
The Msg Object ................................................................................................................................. 17
Modifying the msg Object ............................................................................................................... 20
Example 3: Using the Node-Red Function Node- Beginners Guide .................................................. 22
Accessing the msg Properties in The Function Node. ................................................................. 22
Using the Function Node ................................................................................................................. 23
Simple Function Example 1 ............................................................................................................. 24
Function Node Example 2................................................................................................................ 25
Multiple Outputs................................................................................................................................ 27
Multiple Messages on a Single Output .......................................................................................... 29
Example 4: Storing Data in Node-Red Variables ................................................................................. 32
Using the Context Object ................................................................................................................ 33
Initialising the Variable .................................................................................................................... 33
Using the Flow Object ...................................................................................................................... 36
Using the Global Object ................................................................................................................... 36
Example 5: How to Copy and Export Nodes and Flows in Node-Red............................................... 37
Copy and Paste ................................................................................................................................. 37
Using Export and Import and The Clipboard ................................................................................ 37
Import Problems ............................................................................................................................... 39
Using The Library.............................................................................................................................. 40
Using Library Functions and Flows................................................................................................. 42
The Node-RED UI
Once you have logged in to your FRED account, you’ll see the standard Node-RED UI
which consists of three main panes, as shown in Fig 2.1

Figure 2.1 The Node-RED UI – showing the node palette (left), flow canvas (centre) and
output pane (right)

The main pane is the flow creation workspace in the middle. This is where you drag and
drop nodes and connect them with wires. Along the top of the workspace pane is a set of
tabs. Each tab opens a previously created workspace and shows any flows created using
that workspace.

On the left is the node pane that contains all the built-in nodes that your instance of
Node-RED supports. In the example above, you are seeing the FRED node set which
contains a large selection that has been added to the basic set that comes with Node-
RED. In later lectures you will learn about these nodes and use them to develop new
flows. As you can see, nodes are grouped into categories. Opening up a category shows
the individual nodes.

On the right-hand side is the output pane that can be toggled between the info and
debug tabs. When info is selected, documentation for the selected node is shown
there. When debug is selected, it will display the output of debug nodes, errors and
warnings.

Above these three main panes is the usual toolbar, and on the right-hand side are three
widgets, a deploy button, a user info icon and a pulldown menu for admin and control.
You’ll look in more detail at the pulldown later in these lectures. The user info icon
allows you to return to the FRED front page with links to tutorials, your account
information, status and other information as well as to log out of the FRED service.

The Deploy button is used when a flow has been constructed and causes the flow to be
deployed onto the Node-RED system and executed. You’ll be introduced to the details of
what’s actually happening under the covers in lecture 5 and beyond. For now just treat
the Deploy button as the way to get your flow running.

A quick tour of Node-RED nodes and


messages
As you saw in lecture 1, Node-RED allows you to wire together nodes to create flows
which carry out your programming task. Messages pass between nodes, moving from
input nodes through processing nodes to output nodes. Let’s take a brief look at nodes,
flows and messages.

There are three main types of nodes:

1. Input Nodes (e.g. inject)


2. Output Nodes (e.g. debug)
3. Processing Nodes (e.g. function)

Figure 2.2 The main types of nodes: input, output and processing

Input nodes allow you to input data into a Node-RED application or “flow”. They have at
least one output endpoint represented by the small grey square only on their right side.
You use input nodes to connect data from other services, for example the Twitter,
Google, serial, websockets or tcp nodes, or to manually input data into a flow using the
inject node.
Output nodes allow you to send data outside of a Node-RED flow. They have a single
input endpoint on their left side. You use output nodes to send data to other services, for
example via Twitter, tcp, serial or email nodes, or to use the debug node to output to the
debug pane.

Processing nodes allow you to process data. They have an input endpoint and one or
more output endpoints. They allow you to transform the data type (e.g. json, csv, xml)
nodes, use the data to trigger a message (e.g. trigger, delay) nodes and to write custom
code that uses the data received (e.g. function node).

Note that some nodes, like the inject and debug messages, have a button that allows you
to actuate a node (in the case of the inject node) or to enable and disable a node (in the
case of the debug node).

Flows consist of multiple nodes wired together, with output tabs linked to input tabs of
the next node in the flow. Messages flow along the nodes carrying data from node to
node.

Node-RED nodes consume input messages and produce output messages. Messages are
JavaScript objects that contain at least a “payload” parameter, like this:

Listing 2.1 A basic Node-RED message structure

1. msg = {
2. payload:”message payload”
3. };

Nodes consume and produce messages, usually using msg.payload as the main
placeholder for the data they consume and produce. However, messages can be
extended to contain other parameters. For example, to set the topic of a message and
add a new parameter, location, you could create a new msg object as shown in listing
2.2.

Listing 2.2 A more complex Node-RED message structure

1. msg = {
2. payload:”message payload”,
3. topic:”error”,
4. location:”somewhere in space and time”
5. };

Let’s use this knowledge to create your first flow.


Example 1 Building your first flow:
Hello World
Let’s go ahead and start building your first flow so that you can see how simple it is to
use the Node-RED UI to build and deploy a flow.

Let’s start with the easiest flow possible, a node to inject some information into the flow,
wired to a debug node to see the output from the flow as a debug message. Once you
have that running, you’ll build it up to the full Hello World flow.

Since this is the first time you’ll be shown how to actually build a flow, let’s start slowly
and explain each step with a screen-shot. Once you’ve created your first flow and seen
how easy it is, you’ll mostly be shown a single picture of the final flow rather than all the
screenshots.

Let’s start with the simplest Node, the comment Node. You’ll find this in the function
section of the node palette. Drag and drop a comment node onto the flow workspace as
shown in Fig 2.3.
Figure 2.3: Using a comment node is a great way to add visible comments into flows

Once you’ve done that, take a look at the info pane on the right (remember to switch to
info if the debug tab is selected). You’ll see a little info on the node, including the node
name, a unique ID, and a properties field with a description of the node. For the
comment node there’s not much to say; however, more sophisticated nodes have a lot
more info.

Double-click on the comment node, and you’ll see a configuration window (Fig 2.4) You
can give the comment node a name and add detailed text if you like.

Figure 2.4 Give the comment a name and add any info you want in the text box
Ok, now let’s add the first node that actually does something, an inject node. The
inject node is used to generate input into a flow and is one of the first nodes in the node
palette under input. If you drag and drop an inject node onto the flow workspace, and
then look at the info tab, you’ll see the documentation for the inject node. Note that the
name of the node on the workspace changes from inject to timestamp, because the
default behaviour for the node is to inject a timestamp – the current time in
milliseconds since January 1, 1970.
Fig 2.5 The inject node allows you to insert events as messages, defaulting to a
timestamp

You’ll also notice that the inject node (now named timestamp) has a blue dot top right
and a grey square centre right. The blue dot indicates that the node hasn’t been
deployed since it was last changed; the grey square is the output point for the node. This
is where you attach ‘wires’ that route output message from the inject node to the next
node in the flow.
To get a sense for the inject node and the whole flow deployment process, let’s add a
debug node to see what happens, wire them together and then deploy the flow and test
it.

Start by dragging a debug node from the node palette to the workspace. Again you can
look at the info for the node.

Then you’ll wire the two nodes together. To do that, click on the grey output point for
the inject node and, holding the mouse button down, drag towards the debug node. An
orange wire appears, which you can then attach to the grey input point on the
debug node.

Figure 2.6 Wiring an inject node to a debug node


This is the simplest flow possible and will send the current timestamp to the debug node
for display in the debug pane. Let’s try it!

Click the deploy button in the Node-RED window (top right). You’ll see a pop-up saying
the flow has been successfully deployed. You will also notice that the blue dots on the
nodes disappear, indicating there are no un-deployed changes.

Now, before you try the flow, make sure the the debug tab is selected on the right pane.
Then click on the left tab on the inject node and look at what appears in the debug pane.
Figure 2.7 Debug output from your first flow – the time when you clicked the inject
node.

As you can see, the inject node, when clicked, generates a timestamp (number of
milliseconds since January 1, 1970), which is converted to a message and sent along the
output wire, which is delivered to the debug node as an input message. The
debug node’s default behaviour is to show any message it receives, which it does in the
debug pane on the right.

Congratulations, you created and deployed your first flow!

Let’s now augment it a little to see what else we can do with this simple flow. Firstly,
we’ll edit the inject node to deliver a text message rather than a timestamp. To do that,
select the inject node in the flow and double-click it. You’ll see a configuration window
like the one in Fig 2.8.
Figure 2.8 Editing an inject node to send text instead of a timestamp

In the payload field, select string instead of timestamp and then type any string you like
into the blank field below the payload field. As is traditional, let’s start with “Hello
World – from my first NR flow!”

Once you’ve made the change, click ok to save the changes and take a look at the flow.
You’ll see the blue dot has appeared on the inject node (which has also returned to being
called inject rather than timestamp) to indicate that you have un-deployed changes.
Click the deploy button again to resolve that and then go ahead and click the tab on the
inject node. If you look at the debug output you’ll see that instead of a timestamp, your
text has been delivered as a message to the debug node, which displays it as usual.

Figure 2.9 Sending a text message rather than a timestamp

As you can see, it’s very easy to wire up some simple nodes and get data to pass through
your flow as messages. At this stage, you’ll probably be wondering a little about the
messages that are flowing between nodes. The debug node can be used to examine them
in more detail.

All messages in Node-RED have three default properties: the payload, which we are
seeing above, a message topic, which is a user-defined string describing what the
message is about (its topic, if you will) and an internal identifier. You can actually see
this information if you edit the debug node configuration. Let’s do that and look at the
output (Fig 2.10)
Figure 2.10: setting the debug node to show the internals of a message

Select the debug node, double click and change the node output field to “Complete msg
object”. If you then save this, deploy again and click the inject node, you will see in the
debug pane a JSON structure that contains 3 fields: a “topic” which is currently blank, a
“payload” which contains the string you set in the inject node and an internal ID field
“_msgid”. Generally the internal message ID field isn’t used. However, both the topic
and payload are used extensively when developing flows. You’ll see more of that later in
the lecture series.

These fields are extensible, so you can define new message properties, for example,
msg.location, which could be used to add the latitude and longitude values for the
source of the message. Let’s take a look at that in the next example flow.
Example 2: Understanding The Node-
Red Message Object

A node red flow consists of a series of


interconnected nodes.(wired nodes).

All nodes must have an input and can have 0 or multiple outputs.

Nodes exchange data between each other using the msg object.

Each node receives the message object from the previous node, and can then
pass this message object onto the next node in the flow.

The Msg Object

The Msg Object is a standard JavaScript object and has several existing
properties depending where it originated.

You can see the message properties by sending the msg to the debug node.
By default the debug node will display the msg.payload property but you
can edit the debug node to display all of the message properties.

If you Look at the message object properties of the the inject node.

You will see that is has the following properties

 payload
 topic
 _msgid

A msg object that originates from an MQTT input node has the following
properties:
 payload
 topic
 qos
 _msgid
 retain

as shown in the screen shot below:

The _msgid property is a message identifier added by node read and can be
used to track message objects.

Msg object properties can be any valid JavaScript type e.g.

 String
 Integer
 Object
 Boolean
Modifying the msg Object

Node-red provides various core nodes that can change the messages object
without you having to write any JavaScript code.

The main nodes are change, split, join, switch

You can find out more of what they do by dragging them onto the flow and
then viewing the info tabassociated with them.

See the documentation for more details

There is also the very versatile function node, but it requires writing
JavaScript code.

Accessing the msg Properties

You access the msg properties just like you do any JavaScript object.

The message payload can be accessed using:

var payload=msg.payload;

and can be modified using:


msg.payload=payload;

Likewise the message topic can be accessed using:

var topic=msg.topic;

and can be modified using:

msg.topic= topic;

If you are using a node like the change node then it defaults to payload but
you can change any property by editing the appropriate field as shown below:
Example 3: Using the Node-Red
Function Node- Beginners Guide
The function node is used to run JavaScript code against the msg
object.

The function node accepts a msg object as input and can return 0 or more message
objects as output.

This message object must have a payload property (msg.payload), and usually has
other properties depending on the proceeding nodes.

Accessing the msg Properties in The Function Node.

The message payload can be accessed using:

var payload=msg.payload;

and can be modified using:

msg.payload=payload;

Likewise the message topic can be accessed using:

var topic=msg.topic;

and can be modified using:


msg.topic= topic;

It can be extended using

var newvalue;

msg.newproperty=newvalue;

Now the msg object has a property called msg.newproperty.

Creating a New Message Object

Inside a function you can create a new msg object using:

var newMsg = { payload: msg.payload,topic:msg.topic };

return newMsg;

Using the Function Node

When you drop a function node onto a flow , and go to edit you will see a single line of
code that returns the msg object and a blank line above were you can start to enter
your own code.
If you don’t return a msg object then the flow stops.

Simple Function Example 1

The flow below is uses the function node with the default code which simply returns
the msg object.

The effect is simply to pass the msg object and all of it’s properties from the input node
to the output node and the next node in the flow (debug).
The inject node injects a msg object into the flow with the Unix time stamp as the
payload and a blank topic. It is passes through the do nothing function node and
you can see that this appears on the debug node.

Function Node Example 2

Next we use the inject node to inject a payload with the string “test string” and a
topic of test.

If we pass this into our do nothing function as before we get the following output.
The output is as expected. This time we show the topic as test and the payload as test
string.

Now if we modify the function to change the payload t Upper case and the topic to
upper case using the following code:

var payload=msg.payload; //get payload

msg.payload=payload.toUpperCase(); //convert to uppercase

var topic=msg.payload; //get topic

msg.topic=topic.toUpperCase();//convert to uppercase

return msg;

The first line of the code retrieves the msg payload.

var payload=msg.payload; //get payload

The second line converts it to upper case and re-assign it back to the msg object.

msg.payload=payload.toUpperCase();

We then do exactly the same with the topic property before returning the complete msg
object.

The output on the debug screen is shown below:


Notice the topic and payload have been converted to upper case.

Multiple Outputs

The function node can be configured with multiple outputs.

This is useful when the flow splits into separate paths depending on a message
property.

To configure multiple outputs open the function node and use the up/down arrows to
adjust the outputs.

Outputs are numbered starting with 1 at the top.

To return messages to multiple outputs you need to return an array. So the return looks
like this:

return [msg1,msg2];
Msg1 will appear on output1 and msg2 on output2. To stop a flow you return null.

So to return the msg objext on output1 and nothing on output2 use:

return [msg1,null];

Example

In the example flow we use two inject nodes to inject a message on two different topics
and send the message to the output based on the topic name.

Topic test1 goes to output1 and test2 goes to output2.

The following code is used in the function node to spit the message path based on the
topic name.

Notice the return statement.

var topic=msg.topic;

if (topic=="test1"){
return [msg,null];

if (topic=="test2"){

return [null,msg];

The output on the debug screen is show below:

Multiple Messages on a Single Output

You can use an array to return multiple msg objects on a single output.

So the return would look like this


return [msg_object_array];

Important you are returning an array of objects in an array.

This is best seen with an example

Example Multiple Messages on Single Output:

In this example we use an inject node to inject a test string into the function node.

The function node takes the string and uses it for the message payload, but instead of
sending 1 message it has a for loop which creates 3 messages and puts them in an
array . The function returns the array as an array!

Here is the flow:

Here is the code of the function node:

var m_out=[]; //rray for message objects

var message=msg.payload;

for (i=0;i<3;i++){

message=message+i; //add count to message

var newmsg={payload:message,topic:msg.topic}

m_out.push(newmsg);
}

return[m_out];

Important– notice the return statement returns an array.

Here is the debug screen output when run notice the debug screen shows 3 messages:
Example 4: Storing Data in Node-Red
Variables
Node-red nodes pass the msg object between nodes.

However this object is replaced by the next msg object. So how do you store data
between node calls?

Node-Red provides three mechanisms:

 The context object -stores data for a node


 The Flow object – stores data for a flow
 The global object -stores data for the canvas

I will illustrate these methods using a simple flow like the one below.

The inject node is used to start the flow , then function node implements the counter
and the debug node displays the result.

The idea is to count the number of times the message was injected.

The actual message that gets injected isn’t important.

Note: There is a video to accompany this tutorial as it is easy to demonstrate the


interaction between variables using video. You may want to read quickly through the
text and then go to the video. Here is the video
Using the Context Object

This is used for storing function variables.

The process for retrieving and storing is to use the get method of the object for
retrieving value and the set method to store values.:

x =context.get(name); //to retrieve a variable

context.set(name)=x; // to store a variable

A variable stored for function 1 in the context object is not available to function 2 and
vice versa.

Initialising the Variable

The standard way is to include this code at the top of the script:

var count=context.get('count') || 0;
Which means- If count doesn’t exist in the context object then make our local variable
count zero; otherwise assign the stored value to our local variable count.

You can use multiple variables e.g.

var count=context.get('count') || 0;

var count2=context.get('count2') || 0;

You can also use an object e.g

var local=context.get('data') || {};

if (local.count===undefined) //test exists

local.count=0;

In the code above data is an object stored in the context object and local is our local
object.

Here is an example script that uses a single variable as a counter in function 1:

var count=context.get('count') || 0;

count +=1;

msg.payload="F1 "+msg.payload+" "+count;

context.set('count',count);
return msg;

Here is an example script that uses a object variable as a counter in function 2::

var local=context.get('data') || {};

if (local.count===undefined)//test exists

local.count=0;

local.count +=1;

msg.payload="F2 "+msg.payload+" "+local.count;

context.set('data',local);

return msg;

If look at the code for function 1 and function 2 you will see that they use the same
counter variable..

However when you click the inject node for function 1 you see the counter value is 1
and then the inject node for function 2 then counter is also 1.

This shows that the counters are local to each function and not shared between
functions.

Note: Currently if you restart the flow the variables are reset but this is likely to change
Using the Flow Object

You use the flow object in the same way as the context object.

To retrieve values stored in the flow object use:

var count=flow.get('count') || 0;

and to store values use:

flow.set('count',count);

This time you should notice that the functions can share variables stored in flow
objects. See video

Using the Global Object

You use the flow object in the same way as the context object.

To retrieve values stored in the flow object use:

var count=global.get('count') || 0;

and to store values use:

global.set('count',gcount);

This time you should notice that the functions can share variables stored in the global
object even across flows.
Example 5: How to Copy and Export
Nodes and Flows in Node-Red
There a several ways that you can copy nodes and flows between flows in the node-red
Workspace.

They are:

 Select, Copy and Paste


 Export and Import Clipboard
 Save To and Retrieve from the Local Library

Copy and Paste

This works just like copying text in a word processor. You simply select the nodes you
want using the CTRL key to select individual nodes together into a group
or CTRL+A to select all nodes in the workspace.

Then use CTRL+C to Copy.

You then move to the place on the workspace or open the workspace where you want
to copy the nodes to and use CTRL+V to paste the nodes/flow into the workspace.

Note: This only works for flows in the same workspace.

Using Export and Import and The Clipboard

This method can be used for exchanging flows between systems as well as on the same
system.

To do this you need to highlight each node in the flow and then click
on Menu>export>clipboard.

Note: Use CTRL+A to select all nodes in the workspace.


The contents of the export file will be displayed click on export to clipboard.

You then need to open a file editor and paste the contents into the file using CTRL+V.

Give the file a name and save it.


Importing A Flow

You will need to open the flow in a text editor, and then copy its contents
using CRTL+C.

You then go to Menu>import>clipboard and paste the file into the window and click
the import button to complete the import.

Import Problems

If you find that the import button doesn’t change colour and a red line appears around
the text box it is probably because what you are trying to import isn’t valid JSON.

You can test it by pasting it into this online JSON checker

A confusing issue I found is that my export file verified OK using the JSON checker but
failed when doing an import at a remote location.

The problem was due to smart quotes in the export file.

I pasted the file into this online smart quotes removal tool to remove them, and then
sent it, and it worked OK.
Using The Library

If you want to save a flow or function and reuse it in another flow then you can save it
to the local library.

To save a flow to the library highlight all nodes in the flow by using CTRL+A then use
the main menu (top right) and select Export>Library.

You will need to give the flow a name and optionally you can create a folder for the
flow.

For example you could store flows in the flows folder and functions in the functions
folder.

All flows are stored in the lib folder under the users .node-red folder.

To save a function to the library double click on the function to edit it and click on
the bookmark iconnext to the function name.

A drop down menu appears to either import or save the function to the library.
You need to give the file a name and optionally a folder to store it in.

Note: The function itself should have a name as you will need this when importing the
function.
If you don’t give the function a name it appears as an unnamed function when
importing.

Using Library Functions and Flows

To use a library flow use the Import>Library option and select the flow, and it
appears in the flow canvas

To use a library function drag a function node into the flow canvas then open it for
editing.

Click on the bookmark icon next to the function name and select open library from the
drop down menu.

Open folder containing functions and the functions appear by name. Select the function
and click load, to load the library code into the function.

Vous aimerez peut-être aussi